Commit | Line | Data |
1a7ebbb3 |
1 | |
ce87e388 |
2 | package InstanceCountingClass; |
1a7ebbb3 |
3 | |
4 | use strict; |
5 | use warnings; |
6 | |
7 | use Class::MOP 'meta'; |
8 | |
9 | our $VERSION = '0.01'; |
10 | |
e2f8b029 |
11 | use base 'Class::MOP::Class'; |
1a7ebbb3 |
12 | |
13 | __PACKAGE__->meta->add_attribute( |
14 | Class::MOP::Attribute->new('$:count' => ( |
15 | reader => 'get_count', |
16 | default => 0 |
17 | )) |
18 | ); |
19 | |
20 | sub construct_instance { |
21 | my ($class, %params) = @_; |
22 | $class->{'$:count'}++; |
23 | return $class->SUPER::construct_instance(); |
24 | } |
25 | |
e2f8b029 |
26 | 1; |
27 | |
28 | __END__ |
29 | |
30 | =pod |
31 | |
32 | =head1 NAME |
33 | |
34 | InstanceCountingClass - An example metaclass which counts instances |
35 | |
36 | =head1 SYNOPSIS |
37 | |
38 | package Foo; |
39 | |
40 | sub meta { InstanceCountingClass->initialize($_[0]) } |
41 | sub new { |
42 | my $class = shift; |
43 | bless $class->meta->construct_instance() => $class; |
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 |