2 package Class::MOP::Class;
7 use Class::MOP::Immutable;
8 use Class::MOP::Instance;
9 use Class::MOP::Method::Wrapped;
12 use Scalar::Util 'blessed', 'reftype', 'weaken';
13 use Sub::Name 'subname';
15 our $VERSION = '0.25';
16 our $AUTHORITY = 'cpan:STEVAN';
18 use base 'Class::MOP::Module';
22 sub meta { Class::MOP::Class->initialize(blessed($_[0]) || $_[0]) }
28 my $package_name = shift;
29 (defined $package_name && $package_name && !blessed($package_name))
30 || confess "You must pass a package name and it cannot be blessed";
31 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
34 $class->construct_class_instance('package' => $package_name, @_);
39 my $package_name = shift;
40 (defined $package_name && $package_name && !blessed($package_name))
41 || confess "You must pass a package name and it cannot be blessed";
42 Class::MOP::remove_metaclass_by_name($package_name);
43 $class->construct_class_instance('package' => $package_name, @_);
46 # NOTE: (meta-circularity)
47 # this is a special form of &construct_instance
48 # (see below), which is used to construct class
49 # meta-object instances for any Class::MOP::*
50 # class. All other classes will use the more
51 # normal &construct_instance.
52 sub construct_class_instance {
55 my $package_name = $options{'package'};
56 (defined $package_name && $package_name)
57 || confess "You must pass a package name";
59 # return the metaclass if we have it cached,
60 # and it is still defined (it has not been
61 # reaped by DESTROY yet, which can happen
62 # annoyingly enough during global destruction)
64 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
69 # we need to deal with the possibility
70 # of class immutability here, and then
71 # get the name of the class appropriately
72 $class = (blessed($class)
73 ? ($class->is_immutable
74 ? $class->get_mutable_metaclass_name()
78 # now create the metaclass
80 if ($class eq 'Class::MOP::Class') {
83 # inherited from Class::MOP::Package
84 '$!package' => $package_name,
87 # since the following attributes will
88 # actually be loaded from the symbol
89 # table, and actually bypass the instance
90 # entirely, we can just leave these things
91 # listed here for reference, because they
92 # should not actually have a value associated
94 '%!namespace' => \undef,
95 # inherited from Class::MOP::Module
96 '$!version' => \undef,
97 '$!authority' => \undef,
98 # defined in Class::MOP::Class
99 '@!superclasses' => \undef,
102 '%!attributes' => {},
103 '$!attribute_metaclass' => $options{'attribute_metaclass'} || 'Class::MOP::Attribute',
104 '$!method_metaclass' => $options{'method_metaclass'} || 'Class::MOP::Method',
105 '$!instance_metaclass' => $options{'instance_metaclass'} || 'Class::MOP::Instance',
107 ## uber-private variables
109 # this starts out as undef so that
110 # we can tell the first time the
111 # methods are fetched
113 '$!_package_cache_flag' => undef,
118 # it is safe to use meta here because
119 # class will always be a subclass of
120 # Class::MOP::Class, which defines meta
121 $meta = $class->meta->construct_instance(%options)
124 # and check the metaclass compatibility
125 $meta->check_metaclass_compatability();
127 Class::MOP::store_metaclass_by_name($package_name, $meta);
130 # we need to weaken any anon classes
131 # so that they can call DESTROY properly
132 Class::MOP::weaken_metaclass($package_name) if $meta->is_anon_class;
137 sub reset_package_cache_flag { (shift)->{'$!_package_cache_flag'} = undef }
138 sub update_package_cache_flag {
140 # we can manually update the cache number
141 # since we are actually adding the method
142 # to our cache as well. This avoids us
143 # having to regenerate the method_map.
145 (shift)->{'$!_package_cache_flag'} = Class::MOP::check_package_cache_flag();
148 sub check_metaclass_compatability {
151 # this is always okay ...
152 return if blessed($self) eq 'Class::MOP::Class' &&
153 $self->instance_metaclass eq 'Class::MOP::Instance';
155 my @class_list = $self->linearized_isa;
156 shift @class_list; # shift off $self->name
158 foreach my $class_name (@class_list) {
159 my $meta = Class::MOP::get_metaclass_by_name($class_name) || next;
162 # we need to deal with the possibility
163 # of class immutability here, and then
164 # get the name of the class appropriately
165 my $meta_type = ($meta->is_immutable
166 ? $meta->get_mutable_metaclass_name()
169 ($self->isa($meta_type))
170 || confess $self->name . "->meta => (" . (blessed($self)) . ")" .
171 " is not compatible with the " .
172 $class_name . "->meta => (" . ($meta_type) . ")";
174 # we also need to check that instance metaclasses
175 # are compatabile in the same the class.
176 ($self->instance_metaclass->isa($meta->instance_metaclass))
177 || confess $self->name . "->meta => (" . ($self->instance_metaclass) . ")" .
178 " is not compatible with the " .
179 $class_name . "->meta => (" . ($meta->instance_metaclass) . ")";
187 # this should be sufficient, if you have a
188 # use case where it is not, write a test and
190 my $ANON_CLASS_SERIAL = 0;
193 # we need a sufficiently annoying prefix
194 # this should suffice for now, this is
195 # used in a couple of places below, so
196 # need to put it up here for now.
197 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
201 no warnings 'uninitialized';
202 $self->name =~ /^$ANON_CLASS_PREFIX/ ? 1 : 0;
205 sub create_anon_class {
206 my ($class, %options) = @_;
207 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
208 return $class->create($package_name, %options);
212 # this will only get called for
213 # anon-classes, all other calls
214 # are assumed to occur during
215 # global destruction and so don't
216 # really need to be handled explicitly
219 no warnings 'uninitialized';
220 return unless $self->name =~ /^$ANON_CLASS_PREFIX/;
221 my ($serial_id) = ($self->name =~ /^$ANON_CLASS_PREFIX(\d+)/);
223 foreach my $key (keys %{$ANON_CLASS_PREFIX . $serial_id}) {
224 delete ${$ANON_CLASS_PREFIX . $serial_id}{$key};
226 delete ${'main::' . $ANON_CLASS_PREFIX}{$serial_id . '::'};
231 # creating classes with MOP ...
235 my $package_name = shift;
237 (defined $package_name && $package_name)
238 || confess "You must pass a package name";
241 || confess "You much pass all parameters as name => value pairs " .
242 "(I found an uneven number of params in \@_)";
246 my $code = "package $package_name;";
247 $code .= "\$$package_name\:\:VERSION = '" . $options{version} . "';"
248 if exists $options{version};
249 $code .= "\$$package_name\:\:AUTHORITY = '" . $options{authority} . "';"
250 if exists $options{authority};
253 confess "creation of $package_name failed : $@" if $@;
255 my $meta = $class->initialize($package_name);
257 $meta->add_method('meta' => sub {
258 $class->initialize(blessed($_[0]) || $_[0]);
261 $meta->superclasses(@{$options{superclasses}})
262 if exists $options{superclasses};
264 # process attributes first, so that they can
265 # install accessors, but locally defined methods
266 # can then overwrite them. It is maybe a little odd, but
267 # I think this should be the order of things.
268 if (exists $options{attributes}) {
269 foreach my $attr (@{$options{attributes}}) {
270 $meta->add_attribute($attr);
273 if (exists $options{methods}) {
274 foreach my $method_name (keys %{$options{methods}}) {
275 $meta->add_method($method_name, $options{methods}->{$method_name});
284 # all these attribute readers will be bootstrapped
285 # away in the Class::MOP bootstrap section
287 sub get_attribute_map { $_[0]->{'%!attributes'} }
288 sub attribute_metaclass { $_[0]->{'$!attribute_metaclass'} }
289 sub method_metaclass { $_[0]->{'$!method_metaclass'} }
290 sub instance_metaclass { $_[0]->{'$!instance_metaclass'} }
293 # this is a prime canidate for conversion to XS
297 if (defined $self->{'$!_package_cache_flag'} &&
298 $self->{'$!_package_cache_flag'} == Class::MOP::check_package_cache_flag()) {
299 return $self->{'%!methods'};
302 my $map = $self->{'%!methods'};
304 my $class_name = $self->name;
305 my $method_metaclass = $self->method_metaclass;
307 foreach my $symbol ($self->list_all_package_symbols('CODE')) {
308 my $code = $self->get_package_symbol('&' . $symbol);
310 next if exists $map->{$symbol} &&
311 defined $map->{$symbol} &&
312 $map->{$symbol}->body == $code;
314 my ($pkg, $name) = Class::MOP::get_code_info($code);
315 next if ($pkg || '') ne $class_name &&
316 ($name || '') ne '__ANON__';
318 $map->{$symbol} = $method_metaclass->wrap($code);
324 # Instance Construction & Cloning
329 # we need to protect the integrity of the
330 # Class::MOP::Class singletons here, so we
331 # delegate this to &construct_class_instance
332 # which will deal with the singletons
333 return $class->construct_class_instance(@_)
334 if $class->name->isa('Class::MOP::Class');
335 return $class->construct_instance(@_);
338 sub construct_instance {
339 my ($class, %params) = @_;
340 my $meta_instance = $class->get_meta_instance();
341 my $instance = $meta_instance->create_instance();
342 foreach my $attr ($class->compute_all_applicable_attributes()) {
343 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
346 # this will only work for a HASH instance type
347 if ($class->is_anon_class) {
348 (reftype($instance) eq 'HASH')
349 || confess "Currently only HASH based instances are supported with instance of anon-classes";
351 # At some point we should make this official
352 # as a reserved slot name, but right now I am
353 # going to keep it here.
354 # my $RESERVED_MOP_SLOT = '__MOP__';
355 $instance->{'__MOP__'} = $class;
360 sub get_meta_instance {
362 return $class->instance_metaclass->new(
364 $class->compute_all_applicable_attributes()
370 my $instance = shift;
371 (blessed($instance) && $instance->isa($class->name))
372 || confess "You must pass an instance ($instance) of the metaclass (" . $class->name . ")";
374 # we need to protect the integrity of the
375 # Class::MOP::Class singletons here, they
376 # should not be cloned.
377 return $instance if $instance->isa('Class::MOP::Class');
378 $class->clone_instance($instance, @_);
382 my ($class, $instance, %params) = @_;
384 || confess "You can only clone instances, \$self is not a blessed instance";
385 my $meta_instance = $class->get_meta_instance();
386 my $clone = $meta_instance->clone_instance($instance);
387 foreach my $attr ($class->compute_all_applicable_attributes()) {
388 if (exists $params{$attr->init_arg}) {
389 $meta_instance->set_slot_value($clone, $attr->name, $params{$attr->init_arg});
401 @{$self->get_package_symbol('@ISA')} = @supers;
403 # we need to check the metaclass
404 # compatibility here so that we can
405 # be sure that the superclass is
406 # not potentially creating an issues
407 # we don't know about
408 $self->check_metaclass_compatability();
410 @{$self->get_package_symbol('@ISA')};
416 my $super_class = $self->name;
419 my $find_derived_classes;
420 $find_derived_classes = sub {
421 my ($outer_class) = @_;
423 my $symbol_table_hashref = do { no strict 'refs'; \%{"${outer_class}::"} };
426 for my $symbol ( keys %$symbol_table_hashref ) {
427 next SYMBOL if $symbol !~ /\A (\w+):: \z/x;
428 my $inner_class = $1;
430 next SYMBOL if $inner_class eq 'SUPER'; # skip '*::SUPER'
434 ? "${outer_class}::$inner_class"
437 if ( $class->isa($super_class) and $class ne $super_class ) {
438 push @derived_classes, $class;
441 next SYMBOL if $class eq 'main'; # skip 'main::*'
443 $find_derived_classes->($class);
447 my $root_class = q{};
448 $find_derived_classes->($root_class);
450 undef $find_derived_classes;
452 @derived_classes = sort { $a->isa($b) ? 1 : $b->isa($a) ? -1 : 0 } @derived_classes;
454 return @derived_classes;
460 grep { !($seen{$_}++) } (shift)->class_precedence_list
463 sub class_precedence_list {
466 # We need to check for circular inheritance here.
467 # This will do nothing if all is well, and blow
468 # up otherwise. Yes, it's an ugly hack, better
469 # suggestions are welcome.
470 { ($self->name || return)->isa('This is a test for circular inheritance') }
475 $self->initialize($_)->class_precedence_list()
476 } $self->superclasses()
483 my ($self, $method_name, $method) = @_;
484 (defined $method_name && $method_name)
485 || confess "You must define a method name";
488 if (blessed($method)) {
489 $body = $method->body;
493 ('CODE' eq (reftype($body) || ''))
494 || confess "Your code block must be a CODE reference";
495 $method = $self->method_metaclass->wrap($body);
497 $self->get_method_map->{$method_name} = $method;
499 my $full_method_name = ($self->name . '::' . $method_name);
500 $self->add_package_symbol("&${method_name}" => subname $full_method_name => $body);
501 $self->update_package_cache_flag;
505 my $fetch_and_prepare_method = sub {
506 my ($self, $method_name) = @_;
508 my $method = $self->get_method($method_name);
509 # if we dont have local ...
511 # try to find the next method
512 $method = $self->find_next_method_by_name($method_name);
513 # die if it does not exist
515 || confess "The method '$method_name' is not found in the inheritance hierarchy for class " . $self->name;
516 # and now make sure to wrap it
517 # even if it is already wrapped
518 # because we need a new sub ref
519 $method = Class::MOP::Method::Wrapped->wrap($method);
522 # now make sure we wrap it properly
523 $method = Class::MOP::Method::Wrapped->wrap($method)
524 unless $method->isa('Class::MOP::Method::Wrapped');
526 $self->add_method($method_name => $method);
530 sub add_before_method_modifier {
531 my ($self, $method_name, $method_modifier) = @_;
532 (defined $method_name && $method_name)
533 || confess "You must pass in a method name";
534 my $method = $fetch_and_prepare_method->($self, $method_name);
535 $method->add_before_modifier(subname ':before' => $method_modifier);
538 sub add_after_method_modifier {
539 my ($self, $method_name, $method_modifier) = @_;
540 (defined $method_name && $method_name)
541 || confess "You must pass in a method name";
542 my $method = $fetch_and_prepare_method->($self, $method_name);
543 $method->add_after_modifier(subname ':after' => $method_modifier);
546 sub add_around_method_modifier {
547 my ($self, $method_name, $method_modifier) = @_;
548 (defined $method_name && $method_name)
549 || confess "You must pass in a method name";
550 my $method = $fetch_and_prepare_method->($self, $method_name);
551 $method->add_around_modifier(subname ':around' => $method_modifier);
555 # the methods above used to be named like this:
556 # ${pkg}::${method}:(before|after|around)
557 # but this proved problematic when using one modifier
558 # to wrap multiple methods (something which is likely
559 # to happen pretty regularly IMO). So instead of naming
560 # it like this, I have chosen to just name them purely
561 # with their modifier names, like so:
562 # :(before|after|around)
563 # The fact is that in a stack trace, it will be fairly
564 # evident from the context what method they are attached
565 # to, and so don't need the fully qualified name.
569 my ($self, $method_name, $method) = @_;
570 (defined $method_name && $method_name)
571 || confess "You must define a method name";
573 my $body = (blessed($method) ? $method->body : $method);
574 ('CODE' eq (reftype($body) || ''))
575 || confess "Your code block must be a CODE reference";
577 $self->add_package_symbol("&${method_name}" => $body);
578 $self->update_package_cache_flag;
582 my ($self, $method_name) = @_;
583 (defined $method_name && $method_name)
584 || confess "You must define a method name";
586 return 0 unless exists $self->get_method_map->{$method_name};
591 my ($self, $method_name) = @_;
592 (defined $method_name && $method_name)
593 || confess "You must define a method name";
596 # I don't really need this here, because
597 # if the method_map is missing a key it
598 # will just return undef for me now
599 # return unless $self->has_method($method_name);
601 return $self->get_method_map->{$method_name};
605 my ($self, $method_name) = @_;
606 (defined $method_name && $method_name)
607 || confess "You must define a method name";
609 my $removed_method = delete $self->get_method_map->{$method_name};
611 $self->remove_package_symbol("&${method_name}");
613 $self->update_package_cache_flag;
615 return $removed_method;
618 sub get_method_list {
620 keys %{$self->get_method_map};
623 sub find_method_by_name {
624 my ($self, $method_name) = @_;
625 (defined $method_name && $method_name)
626 || confess "You must define a method name to find";
627 foreach my $class ($self->linearized_isa) {
628 # fetch the meta-class ...
629 my $meta = $self->initialize($class);
630 return $meta->get_method($method_name)
631 if $meta->has_method($method_name);
636 sub compute_all_applicable_methods {
638 my (@methods, %seen_method);
639 foreach my $class ($self->linearized_isa) {
640 # fetch the meta-class ...
641 my $meta = $self->initialize($class);
642 foreach my $method_name ($meta->get_method_list()) {
643 next if exists $seen_method{$method_name};
644 $seen_method{$method_name}++;
646 name => $method_name,
648 code => $meta->get_method($method_name)
655 sub find_all_methods_by_name {
656 my ($self, $method_name) = @_;
657 (defined $method_name && $method_name)
658 || confess "You must define a method name to find";
660 foreach my $class ($self->linearized_isa) {
661 # fetch the meta-class ...
662 my $meta = $self->initialize($class);
664 name => $method_name,
666 code => $meta->get_method($method_name)
667 } if $meta->has_method($method_name);
672 sub find_next_method_by_name {
673 my ($self, $method_name) = @_;
674 (defined $method_name && $method_name)
675 || confess "You must define a method name to find";
676 my @cpl = $self->linearized_isa;
677 shift @cpl; # discard ourselves
678 foreach my $class (@cpl) {
679 # fetch the meta-class ...
680 my $meta = $self->initialize($class);
681 return $meta->get_method($method_name)
682 if $meta->has_method($method_name);
691 # either we have an attribute object already
692 # or we need to create one from the args provided
693 my $attribute = blessed($_[0]) ? $_[0] : $self->attribute_metaclass->new(@_);
694 # make sure it is derived from the correct type though
695 ($attribute->isa('Class::MOP::Attribute'))
696 || confess "Your attribute must be an instance of Class::MOP::Attribute (or a subclass)";
698 # first we attach our new attribute
699 # because it might need certain information
700 # about the class which it is attached to
701 $attribute->attach_to_class($self);
703 # then we remove attributes of a conflicting
704 # name here so that we can properly detach
705 # the old attr object, and remove any
706 # accessors it would have generated
707 $self->remove_attribute($attribute->name)
708 if $self->has_attribute($attribute->name);
710 # then onto installing the new accessors
711 $attribute->install_accessors();
712 $self->get_attribute_map->{$attribute->name} = $attribute;
716 my ($self, $attribute_name) = @_;
717 (defined $attribute_name && $attribute_name)
718 || confess "You must define an attribute name";
719 exists $self->get_attribute_map->{$attribute_name} ? 1 : 0;
723 my ($self, $attribute_name) = @_;
724 (defined $attribute_name && $attribute_name)
725 || confess "You must define an attribute name";
726 return $self->get_attribute_map->{$attribute_name}
728 # this will return undef anyway, so no need ...
729 # if $self->has_attribute($attribute_name);
733 sub remove_attribute {
734 my ($self, $attribute_name) = @_;
735 (defined $attribute_name && $attribute_name)
736 || confess "You must define an attribute name";
737 my $removed_attribute = $self->get_attribute_map->{$attribute_name};
738 return unless defined $removed_attribute;
739 delete $self->get_attribute_map->{$attribute_name};
740 $removed_attribute->remove_accessors();
741 $removed_attribute->detach_from_class();
742 return $removed_attribute;
745 sub get_attribute_list {
747 keys %{$self->get_attribute_map};
750 sub compute_all_applicable_attributes {
752 my (@attrs, %seen_attr);
753 foreach my $class ($self->linearized_isa) {
754 # fetch the meta-class ...
755 my $meta = $self->initialize($class);
756 foreach my $attr_name ($meta->get_attribute_list()) {
757 next if exists $seen_attr{$attr_name};
758 $seen_attr{$attr_name}++;
759 push @attrs => $meta->get_attribute($attr_name);
765 sub find_attribute_by_name {
766 my ($self, $attr_name) = @_;
767 foreach my $class ($self->linearized_isa) {
768 # fetch the meta-class ...
769 my $meta = $self->initialize($class);
770 return $meta->get_attribute($attr_name)
771 if $meta->has_attribute($attr_name);
779 sub is_immutable { 0 }
782 # Why I changed this (groditi)
783 # - One Metaclass may have many Classes through many Metaclass instances
784 # - One Metaclass should only have one Immutable Transformer instance
785 # - Each Class may have different Immutabilizing options
786 # - Therefore each Metaclass instance may have different Immutabilizing options
787 # - We need to store one Immutable Transformer instance per Metaclass
788 # - We need to store one set of Immutable Transformer options per Class
789 # - Upon make_mutable we may delete the Immutabilizing options
790 # - We could clean the immutable Transformer instance when there is no more
791 # immutable Classes of that type, but we can also keep it in case
792 # another class with this same Metaclass becomes immutable. It is a case
793 # of trading of storing an instance to avoid unnecessary instantiations of
794 # Immutable Transformers. You may view this as a memory leak, however
795 # Because we have few Metaclasses, in practice it seems acceptable
796 # - To allow Immutable Transformers instances to be cleaned up we could weaken
797 # the reference stored in $IMMUTABLE_TRANSFORMERS{$class} and ||= should DWIM
800 my %IMMUTABLE_TRANSFORMERS;
801 my %IMMUTABLE_OPTIONS;
805 my $class = blessed $self || $self;
807 $IMMUTABLE_TRANSFORMERS{$class} ||= $self->create_immutable_transformer;
808 my $transformer = $IMMUTABLE_TRANSFORMERS{$class};
810 $transformer->make_metaclass_immutable($self, %options);
811 $IMMUTABLE_OPTIONS{$self->name} =
812 { %options, IMMUTABLE_TRANSFORMER => $transformer };
814 if( exists $options{debug} && $options{debug} ){
815 print STDERR "# of Metaclass options: ", keys %IMMUTABLE_OPTIONS;
816 print STDERR "# of Immutable transformers: ", keys %IMMUTABLE_TRANSFORMERS;
822 return if $self->is_mutable;
823 my $options = delete $IMMUTABLE_OPTIONS{$self->name};
824 confess "unable to find immutabilizing options" unless ref $options;
825 my $transformer = delete $options->{IMMUTABLE_TRANSFORMER};
826 $transformer->make_metaclass_mutable($self, %$options);
830 sub create_immutable_transformer {
832 my $class = Class::MOP::Immutable->new($self, {
833 read_only => [qw/superclasses/],
841 remove_package_symbol
844 class_precedence_list => 'ARRAY',
845 linearized_isa => 'ARRAY',
846 compute_all_applicable_attributes => 'ARRAY',
847 get_meta_instance => 'SCALAR',
848 get_method_map => 'SCALAR',
862 Class::MOP::Class - Class Meta Object
866 # assuming that class Foo
867 # has been defined, you can
869 # use this for introspection ...
871 # add a method to Foo ...
872 Foo->meta->add_method('bar' => sub { ... })
874 # get a list of all the classes searched
875 # the method dispatcher in the correct order
876 Foo->meta->class_precedence_list()
878 # remove a method from Foo
879 Foo->meta->remove_method('bar');
881 # or use this to actually create classes ...
883 Class::MOP::Class->create('Bar' => (
885 superclasses => [ 'Foo' ],
887 Class::MOP:::Attribute->new('$bar'),
888 Class::MOP:::Attribute->new('$baz'),
891 calculate_bar => sub { ... },
892 construct_baz => sub { ... }
898 This is the largest and currently most complex part of the Perl 5
899 meta-object protocol. It controls the introspection and
900 manipulation of Perl 5 classes (and it can create them too). The
901 best way to understand what this module can do, is to read the
902 documentation for each of it's methods.
906 =head2 Self Introspection
912 This will return a B<Class::MOP::Class> instance which is related
913 to this class. Thereby allowing B<Class::MOP::Class> to actually
916 As with B<Class::MOP::Attribute>, B<Class::MOP> will actually
917 bootstrap this module by installing a number of attribute meta-objects
918 into it's metaclass. This will allow this class to reap all the benifits
919 of the MOP when subclassing it.
923 =head2 Class construction
925 These methods will handle creating B<Class::MOP::Class> objects,
926 which can be used to both create new classes, and analyze
927 pre-existing classes.
929 This module will internally store references to all the instances
930 you create with these methods, so that they do not need to be
931 created any more than nessecary. Basically, they are singletons.
935 =item B<create ($package_name,
936 version =E<gt> ?$version,
937 authority =E<gt> ?$authority,
938 superclasses =E<gt> ?@superclasses,
939 methods =E<gt> ?%methods,
940 attributes =E<gt> ?%attributes)>
942 This returns a B<Class::MOP::Class> object, bringing the specified
943 C<$package_name> into existence and adding any of the C<$version>,
944 C<$authority>, C<@superclasses>, C<%methods> and C<%attributes> to
947 =item B<create_anon_class (superclasses =E<gt> ?@superclasses,
948 methods =E<gt> ?%methods,
949 attributes =E<gt> ?%attributes)>
951 This will create an anonymous class, it works much like C<create> but
952 it does not need a C<$package_name>. Instead it will create a suitably
953 unique package name for you to stash things into.
955 On very important distinction is that anon classes are destroyed once
956 the metaclass they are attached to goes out of scope. In the DESTROY
957 method, the created package will be removed from the symbol table.
959 It is also worth noting that any instances created with an anon-class
960 will keep a special reference to the anon-meta which will prevent the
961 anon-class from going out of scope until all instances of it have also
962 been destroyed. This however only works for HASH based instance types,
963 as we use a special reserved slot (C<__MOP__>) to store this.
965 =item B<initialize ($package_name, %options)>
967 This initializes and returns returns a B<Class::MOP::Class> object
968 for a given a C<$package_name>.
970 =item B<reinitialize ($package_name, %options)>
972 This removes the old metaclass, and creates a new one in it's place.
973 Do B<not> use this unless you really know what you are doing, it could
974 very easily make a very large mess of your program.
976 =item B<construct_class_instance (%options)>
978 This will construct an instance of B<Class::MOP::Class>, it is
979 here so that we can actually "tie the knot" for B<Class::MOP::Class>
980 to use C<construct_instance> once all the bootstrapping is done. This
981 method is used internally by C<initialize> and should never be called
982 from outside of that method really.
984 =item B<check_metaclass_compatability>
986 This method is called as the very last thing in the
987 C<construct_class_instance> method. This will check that the
988 metaclass you are creating is compatible with the metaclasses of all
989 your ancestors. For more inforamtion about metaclass compatibility
990 see the C<About Metaclass compatibility> section in L<Class::MOP>.
992 =item B<update_package_cache_flag>
994 This will reset the package cache flag for this particular metaclass
995 it is basically the value of the C<Class::MOP::get_package_cache_flag>
996 function. This is very rarely needed from outside of C<Class::MOP::Class>
997 but in some cases you might want to use it, so it is here.
999 =item B<reset_package_cache_flag>
1001 Clear this flag, used in Moose.
1005 =head2 Object instance construction and cloning
1007 These methods are B<entirely optional>, it is up to you whether you want
1012 =item B<instance_metaclass>
1014 =item B<get_meta_instance>
1016 =item B<new_object (%params)>
1018 This is a convience method for creating a new object of the class, and
1019 blessing it into the appropriate package as well. Ideally your class
1020 would call a C<new> this method like so:
1023 my ($class, %param) = @_;
1024 $class->meta->new_object(%params);
1027 Of course the ideal place for this would actually be in C<UNIVERSAL::>
1028 but that is considered bad style, so we do not do that.
1030 =item B<construct_instance (%params)>
1032 This method is used to construct an instace structure suitable for
1033 C<bless>-ing into your package of choice. It works in conjunction
1034 with the Attribute protocol to collect all applicable attributes.
1036 This will construct and instance using a HASH ref as storage
1037 (currently only HASH references are supported). This will collect all
1038 the applicable attributes and layout out the fields in the HASH ref,
1039 it will then initialize them using either use the corresponding key
1040 in C<%params> or any default value or initializer found in the
1041 attribute meta-object.
1043 =item B<clone_object ($instance, %params)>
1045 This is a convience method for cloning an object instance, then
1046 blessing it into the appropriate package. This method will call
1047 C<clone_instance>, which performs a shallow copy of the object,
1048 see that methods documentation for more details. Ideally your
1049 class would call a C<clone> this method like so:
1051 sub MyClass::clone {
1052 my ($self, %param) = @_;
1053 $self->meta->clone_object($self, %params);
1056 Of course the ideal place for this would actually be in C<UNIVERSAL::>
1057 but that is considered bad style, so we do not do that.
1059 =item B<clone_instance($instance, %params)>
1061 This method is a compliment of C<construct_instance> (which means if
1062 you override C<construct_instance>, you need to override this one too),
1063 and clones the instance shallowly.
1065 The cloned structure returned is (like with C<construct_instance>) an
1066 unC<bless>ed HASH reference, it is your responsibility to then bless
1067 this cloned structure into the right class (which C<clone_object> will
1070 As of 0.11, this method will clone the C<$instance> structure shallowly,
1071 as opposed to the deep cloning implemented in prior versions. After much
1072 thought, research and discussion, I have decided that anything but basic
1073 shallow cloning is outside the scope of the meta-object protocol. I
1074 think Yuval "nothingmuch" Kogman put it best when he said that cloning
1075 is too I<context-specific> to be part of the MOP.
1079 =head2 Informational
1081 These are a few predicate methods for asking information about the class.
1085 =item B<is_anon_class>
1087 This returns true if the class is a C<Class::MOP::Class> created anon class.
1091 This returns true if the class is still mutable.
1093 =item B<is_immutable>
1095 This returns true if the class has been made immutable.
1099 =head2 Inheritance Relationships
1103 =item B<superclasses (?@superclasses)>
1105 This is a read-write attribute which represents the superclass
1106 relationships of the class the B<Class::MOP::Class> instance is
1107 associated with. Basically, it can get and set the C<@ISA> for you.
1110 Perl will occasionally perform some C<@ISA> and method caching, if
1111 you decide to change your superclass relationship at runtime (which
1112 is quite insane and very much not recommened), then you should be
1113 aware of this and the fact that this module does not make any
1114 attempt to address this issue.
1116 =item B<class_precedence_list>
1118 This computes the a list of all the class's ancestors in the same order
1119 in which method dispatch will be done. This is similair to
1120 what B<Class::ISA::super_path> does, but we don't remove duplicate names.
1122 =item B<linearized_isa>
1124 This returns a list based on C<class_precedence_list> but with all
1129 This returns a list of subclasses for this class.
1137 =item B<get_method_map>
1139 =item B<method_metaclass>
1141 =item B<add_method ($method_name, $method)>
1143 This will take a C<$method_name> and CODE reference to that
1144 C<$method> and install it into the class's package.
1147 This does absolutely nothing special to C<$method>
1148 other than use B<Sub::Name> to make sure it is tagged with the
1149 correct name, and therefore show up correctly in stack traces and
1152 =item B<alias_method ($method_name, $method)>
1154 This will take a C<$method_name> and CODE reference to that
1155 C<$method> and alias the method into the class's package.
1158 Unlike C<add_method>, this will B<not> try to name the
1159 C<$method> using B<Sub::Name>, it only aliases the method in
1160 the class's package.
1162 =item B<has_method ($method_name)>
1164 This just provides a simple way to check if the class implements
1165 a specific C<$method_name>. It will I<not> however, attempt to check
1166 if the class inherits the method (use C<UNIVERSAL::can> for that).
1168 This will correctly handle functions defined outside of the package
1169 that use a fully qualified name (C<sub Package::name { ... }>).
1171 This will correctly handle functions renamed with B<Sub::Name> and
1172 installed using the symbol tables. However, if you are naming the
1173 subroutine outside of the package scope, you must use the fully
1174 qualified name, including the package name, for C<has_method> to
1175 correctly identify it.
1177 This will attempt to correctly ignore functions imported from other
1178 packages using B<Exporter>. It breaks down if the function imported
1179 is an C<__ANON__> sub (such as with C<use constant>), which very well
1180 may be a valid method being applied to the class.
1182 In short, this method cannot always be trusted to determine if the
1183 C<$method_name> is actually a method. However, it will DWIM about
1184 90% of the time, so it's a small trade off I think.
1186 =item B<get_method ($method_name)>
1188 This will return a Class::MOP::Method instance related to the specified
1189 C<$method_name>, or return undef if that method does not exist.
1191 The Class::MOP::Method is codifiable, so you can use it like a normal
1192 CODE reference, see L<Class::MOP::Method> for more information.
1194 =item B<find_method_by_name ($method_name>
1196 This will return a CODE reference of the specified C<$method_name>,
1197 or return undef if that method does not exist.
1199 Unlike C<get_method> this will also look in the superclasses.
1201 =item B<remove_method ($method_name)>
1203 This will attempt to remove a given C<$method_name> from the class.
1204 It will return the CODE reference that it has removed, and will
1205 attempt to use B<Sub::Name> to clear the methods associated name.
1207 =item B<get_method_list>
1209 This will return a list of method names for all I<locally> defined
1210 methods. It does B<not> provide a list of all applicable methods,
1211 including any inherited ones. If you want a list of all applicable
1212 methods, use the C<compute_all_applicable_methods> method.
1214 =item B<compute_all_applicable_methods>
1216 This will return a list of all the methods names this class will
1217 respond to, taking into account inheritance. The list will be a list of
1218 HASH references, each one containing the following information; method
1219 name, the name of the class in which the method lives and a CODE
1220 reference for the actual method.
1222 =item B<find_all_methods_by_name ($method_name)>
1224 This will traverse the inheritence hierarchy and locate all methods
1225 with a given C<$method_name>. Similar to
1226 C<compute_all_applicable_methods> it returns a list of HASH references
1227 with the following information; method name (which will always be the
1228 same as C<$method_name>), the name of the class in which the method
1229 lives and a CODE reference for the actual method.
1231 The list of methods produced is a distinct list, meaning there are no
1232 duplicates in it. This is especially useful for things like object
1233 initialization and destruction where you only want the method called
1234 once, and in the correct order.
1236 =item B<find_next_method_by_name ($method_name)>
1238 This will return the first method to match a given C<$method_name> in
1239 the superclasses, this is basically equivalent to calling
1240 C<SUPER::$method_name>, but it can be dispatched at runtime.
1244 =head2 Method Modifiers
1246 Method modifiers are a concept borrowed from CLOS, in which a method
1247 can be wrapped with I<before>, I<after> and I<around> method modifiers
1248 that will be called everytime the method is called.
1250 =head3 How method modifiers work?
1252 Method modifiers work by wrapping the original method and then replacing
1253 it in the classes symbol table. The wrappers will handle calling all the
1254 modifiers in the appropariate orders and preserving the calling context
1255 for the original method.
1257 Each method modifier serves a particular purpose, which may not be
1258 obvious to users of other method wrapping modules. To start with, the
1259 return values of I<before> and I<after> modifiers are ignored. This is
1260 because thier purpose is B<not> to filter the input and output of the
1261 primary method (this is done with an I<around> modifier). This may seem
1262 like an odd restriction to some, but doing this allows for simple code
1263 to be added at the begining or end of a method call without jeapordizing
1264 the normal functioning of the primary method or placing any extra
1265 responsibility on the code of the modifier. Of course if you have more
1266 complex needs, then use the I<around> modifier, which uses a variation
1267 of continutation passing style to allow for a high degree of flexibility.
1269 Before and around modifiers are called in last-defined-first-called order,
1270 while after modifiers are called in first-defined-first-called order. So
1271 the call tree might looks something like this:
1281 To see examples of using method modifiers, see the following examples
1282 included in the distribution; F<InstanceCountingClass>, F<Perl6Attribute>,
1283 F<AttributesWithHistory> and F<C3MethodDispatchOrder>. There is also a
1284 classic CLOS usage example in the test F<017_add_method_modifier.t>.
1286 =head3 What is the performance impact?
1288 Of course there is a performance cost associated with method modifiers,
1289 but we have made every effort to make that cost be directly proportional
1290 to the amount of modifier features you utilize.
1292 The wrapping method does it's best to B<only> do as much work as it
1293 absolutely needs to. In order to do this we have moved some of the
1294 performance costs to set-up time, where they are easier to amortize.
1296 All this said, my benchmarks have indicated the following:
1298 simple wrapper with no modifiers 100% slower
1299 simple wrapper with simple before modifier 400% slower
1300 simple wrapper with simple after modifier 450% slower
1301 simple wrapper with simple around modifier 500-550% slower
1302 simple wrapper with all 3 modifiers 1100% slower
1304 These numbers may seem daunting, but you must remember, every feature
1305 comes with some cost. To put things in perspective, just doing a simple
1306 C<AUTOLOAD> which does nothing but extract the name of the method called
1307 and return it costs about 400% over a normal method call.
1311 =item B<add_before_method_modifier ($method_name, $code)>
1313 This will wrap the method at C<$method_name> and the supplied C<$code>
1314 will be passed the C<@_> arguments, and called before the original
1315 method is called. As specified above, the return value of the I<before>
1316 method modifiers is ignored, and it's ability to modify C<@_> is
1317 fairly limited. If you need to do either of these things, use an
1318 C<around> method modifier.
1320 =item B<add_after_method_modifier ($method_name, $code)>
1322 This will wrap the method at C<$method_name> so that the original
1323 method will be called, it's return values stashed, and then the
1324 supplied C<$code> will be passed the C<@_> arguments, and called.
1325 As specified above, the return value of the I<after> method
1326 modifiers is ignored, and it cannot modify the return values of
1327 the original method. If you need to do either of these things, use an
1328 C<around> method modifier.
1330 =item B<add_around_method_modifier ($method_name, $code)>
1332 This will wrap the method at C<$method_name> so that C<$code>
1333 will be called and passed the original method as an extra argument
1334 at the begining of the C<@_> argument list. This is a variation of
1335 continuation passing style, where the function prepended to C<@_>
1336 can be considered a continuation. It is up to C<$code> if it calls
1337 the original method or not, there is no restriction on what the
1338 C<$code> can or cannot do.
1344 It should be noted that since there is no one consistent way to define
1345 the attributes of a class in Perl 5. These methods can only work with
1346 the information given, and can not easily discover information on
1347 their own. See L<Class::MOP::Attribute> for more details.
1351 =item B<attribute_metaclass>
1353 =item B<get_attribute_map>
1355 =item B<add_attribute ($attribute_meta_object | $attribute_name, %attribute_spec)>
1357 This stores the C<$attribute_meta_object> (or creates one from the
1358 C<$attribute_name> and C<%attribute_spec>) in the B<Class::MOP::Class>
1359 instance associated with the given class. Unlike methods, attributes
1360 within the MOP are stored as meta-information only. They will be used
1361 later to construct instances from (see C<construct_instance> above).
1362 More details about the attribute meta-objects can be found in the
1363 L<Class::MOP::Attribute> or the L<Class::MOP/The Attribute protocol>
1366 It should be noted that any accessor, reader/writer or predicate
1367 methods which the C<$attribute_meta_object> has will be installed
1368 into the class at this time.
1371 If an attribute already exists for C<$attribute_name>, the old one
1372 will be removed (as well as removing all it's accessors), and then
1375 =item B<has_attribute ($attribute_name)>
1377 Checks to see if this class has an attribute by the name of
1378 C<$attribute_name> and returns a boolean.
1380 =item B<get_attribute ($attribute_name)>
1382 Returns the attribute meta-object associated with C<$attribute_name>,
1383 if none is found, it will return undef.
1385 =item B<remove_attribute ($attribute_name)>
1387 This will remove the attribute meta-object stored at
1388 C<$attribute_name>, then return the removed attribute meta-object.
1391 Removing an attribute will only affect future instances of
1392 the class, it will not make any attempt to remove the attribute from
1393 any existing instances of the class.
1395 It should be noted that any accessor, reader/writer or predicate
1396 methods which the attribute meta-object stored at C<$attribute_name>
1397 has will be removed from the class at this time. This B<will> make
1398 these attributes somewhat inaccessable in previously created
1399 instances. But if you are crazy enough to do this at runtime, then
1400 you are crazy enough to deal with something like this :).
1402 =item B<get_attribute_list>
1404 This returns a list of attribute names which are defined in the local
1405 class. If you want a list of all applicable attributes for a class,
1406 use the C<compute_all_applicable_attributes> method.
1408 =item B<compute_all_applicable_attributes>
1410 This will traverse the inheritance heirachy and return a list of all
1411 the applicable attributes for this class. It does not construct a
1412 HASH reference like C<compute_all_applicable_methods> because all
1413 that same information is discoverable through the attribute
1416 =item B<find_attribute_by_name ($attr_name)>
1418 This method will traverse the inheritance heirachy and find the
1419 first attribute whose name matches C<$attr_name>, then return it.
1420 It will return undef if nothing is found.
1424 =head2 Class Immutability
1428 =item B<make_immutable (%options)>
1430 This method will invoke a tranforamtion upon the class which will
1431 make it immutable. Details of this transformation can be found in
1432 the L<Class::MOP::Immutable> documentation.
1434 =item B<make_mutable>
1436 This method will reverse tranforamtion upon the class which
1439 =item B<create_immutable_transformer>
1441 Create a transformer suitable for making this class immutable
1447 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1449 =head1 COPYRIGHT AND LICENSE
1451 Copyright 2006, 2007 by Infinity Interactive, Inc.
1453 L<http://www.iinteractive.com>
1455 This library is free software; you can redistribute it and/or modify
1456 it under the same terms as Perl itself.