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