Commit | Line | Data |
1a7ebbb3 |
1 | |
9ec169fe |
2 | package # hide the package from PAUSE |
3 | InstanceCountingClass; |
1a7ebbb3 |
4 | |
5 | use strict; |
6 | use warnings; |
7 | |
8 | use Class::MOP 'meta'; |
9 | |
10 | our $VERSION = '0.01'; |
11 | |
e2f8b029 |
12 | use base 'Class::MOP::Class'; |
1a7ebbb3 |
13 | |
14 | __PACKAGE__->meta->add_attribute( |
15 | Class::MOP::Attribute->new('$:count' => ( |
16 | reader => 'get_count', |
17 | default => 0 |
18 | )) |
19 | ); |
20 | |
21 | sub construct_instance { |
22 | my ($class, %params) = @_; |
23 | $class->{'$:count'}++; |
24 | return $class->SUPER::construct_instance(); |
25 | } |
26 | |
e2f8b029 |
27 | 1; |
28 | |
29 | __END__ |
30 | |
31 | =pod |
32 | |
33 | =head1 NAME |
34 | |
35 | InstanceCountingClass - An example metaclass which counts instances |
36 | |
37 | =head1 SYNOPSIS |
38 | |
39 | package Foo; |
40 | |
41 | sub meta { InstanceCountingClass->initialize($_[0]) } |
42 | sub new { |
43 | my $class = shift; |
d6fbcd05 |
44 | bless $class->meta->construct_instance(@_) => $class; |
e2f8b029 |
45 | } |
46 | |
47 | # ... meanwhile, somewhere in the code |
48 | |
49 | my $foo = Foo->new(); |
50 | print Foo->meta->get_count(); # prints 1 |
51 | |
52 | my $foo2 = Foo->new(); |
53 | print Foo->meta->get_count(); # prints 2 |
54 | |
55 | # ... etc etc etc |
56 | |
57 | =head1 DESCRIPTION |
58 | |
59 | This is a classic example of a metaclass which keeps a count of each |
60 | instance which is created. |
61 | |
62 | =head1 AUTHOR |
63 | |
64 | Stevan Little E<lt>stevan@iinteractive.comE<gt> |
65 | |
66 | =head1 COPYRIGHT AND LICENSE |
67 | |
68 | Copyright 2006 by Infinity Interactive, Inc. |
69 | |
70 | L<http://www.iinteractive.com> |
71 | |
72 | This library is free software; you can redistribute it and/or modify |
73 | it under the same terms as Perl itself. |
74 | |
75 | =cut |