InstanceCountingClass - An example metaclass which counts instances


Moose documentation Contained in the Moose distribution.

Index


Code Index:

NAME

Top

InstanceCountingClass - An example metaclass which counts instances

SYNOPSIS

Top

  package Foo;

  use metaclass 'InstanceCountingClass';

  sub new  {
      my $class = shift;
      $class->meta->new_object(@_);
  }

  # ... meanwhile, somewhere in the code

  my $foo = Foo->new();
  print Foo->meta->get_count(); # prints 1

  my $foo2 = Foo->new();
  print Foo->meta->get_count(); # prints 2  

  # ... etc etc etc

DESCRIPTION

Top

This is a classic example of a metaclass which keeps a count of each instance which is created.

AUTHORS

Top

Stevan Little <stevan@iinteractive.com>

Yuval Kogman <nothingmuch@woobling.com>

COPYRIGHT AND LICENSE

Top


Moose documentation Contained in the Moose distribution.

package # hide the package from PAUSE
    InstanceCountingClass;

use strict;
use warnings;

our $VERSION = '0.03';

use base 'Class::MOP::Class';

InstanceCountingClass->meta->add_attribute('count' => (
    reader  => 'get_count',
    default => 0
));

InstanceCountingClass->meta->add_before_method_modifier('_construct_instance' => sub {
    my ($class) = @_;
    $class->{'count'}++;	
});

1;

__END__