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