2 package Class::MOP::Class;
7 use Class::MOP::Instance;
8 use Class::MOP::Method::Wrapped;
9 use Class::MOP::Method::Accessor;
10 use Class::MOP::Method::Constructor;
13 use Scalar::Util 'blessed', 'reftype', 'weaken';
14 use Sub::Name 'subname';
15 use Devel::GlobalDestruction 'in_global_destruction';
17 use List::MoreUtils 'all';
19 our $VERSION = '1.01';
20 $VERSION = eval $VERSION;
21 our $AUTHORITY = 'cpan:STEVAN';
23 use base 'Class::MOP::Module',
24 'Class::MOP::Mixin::HasAttributes',
25 'Class::MOP::Mixin::HasMethods';
35 $package_name = shift;
38 $package_name = $options{package};
41 ($package_name && !ref($package_name))
42 || confess "You must pass a package name and it cannot be blessed";
44 return Class::MOP::get_metaclass_by_name($package_name)
45 || $class->_construct_class_instance(package => $package_name, @_);
48 # NOTE: (meta-circularity)
49 # this is a special form of _construct_instance
50 # (see below), which is used to construct class
51 # meta-object instances for any Class::MOP::*
52 # class. All other classes will use the more
53 # normal &construct_instance.
54 sub _construct_class_instance {
56 my $options = @_ == 1 ? $_[0] : {@_};
57 my $package_name = $options->{package};
58 (defined $package_name && $package_name)
59 || confess "You must pass a package name";
61 # return the metaclass if we have it cached,
62 # and it is still defined (it has not been
63 # reaped by DESTROY yet, which can happen
64 # annoyingly enough during global destruction)
66 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
71 # we need to deal with the possibility
72 # of class immutability here, and then
73 # get the name of the class appropriately
75 ? ($class->is_immutable
76 ? $class->_get_mutable_metaclass_name()
80 # now create the metaclass
82 if ($class eq 'Class::MOP::Class') {
83 $meta = $class->_new($options);
87 # it is safe to use meta here because
88 # class will always be a subclass of
89 # Class::MOP::Class, which defines meta
90 $meta = $class->meta->_construct_instance($options)
93 # and check the metaclass compatibility
94 $meta->_check_metaclass_compatibility();
96 Class::MOP::store_metaclass_by_name($package_name, $meta);
99 # we need to weaken any anon classes
100 # so that they can call DESTROY properly
101 Class::MOP::weaken_metaclass($package_name) if $meta->is_anon_class;
109 return Class::MOP::Class->initialize($class)->new_object(@_)
110 if $class ne __PACKAGE__;
112 my $options = @_ == 1 ? $_[0] : {@_};
115 # inherited from Class::MOP::Package
116 'package' => $options->{package},
119 # since the following attributes will
120 # actually be loaded from the symbol
121 # table, and actually bypass the instance
122 # entirely, we can just leave these things
123 # listed here for reference, because they
124 # should not actually have a value associated
126 'namespace' => \undef,
129 # inherited from Class::MOP::Module
131 'authority' => \undef,
133 # defined in Class::MOP::Class
134 'superclasses' => \undef,
137 'attribute_metaclass' =>
138 ( $options->{'attribute_metaclass'} || 'Class::MOP::Attribute' ),
139 'method_metaclass' =>
140 ( $options->{'method_metaclass'} || 'Class::MOP::Method' ),
141 'wrapped_method_metaclass' => (
142 $options->{'wrapped_method_metaclass'}
143 || 'Class::MOP::Method::Wrapped'
145 'instance_metaclass' =>
146 ( $options->{'instance_metaclass'} || 'Class::MOP::Instance' ),
147 'immutable_trait' => (
148 $options->{'immutable_trait'}
149 || 'Class::MOP::Class::Immutable::Trait'
151 'constructor_name' => ( $options->{constructor_name} || 'new' ),
152 'constructor_class' => (
153 $options->{constructor_class} || 'Class::MOP::Method::Constructor'
155 'destructor_class' => $options->{destructor_class},
159 sub reset_package_cache_flag { (shift)->{'_package_cache_flag'} = undef }
160 sub update_package_cache_flag {
163 # we can manually update the cache number
164 # since we are actually adding the method
165 # to our cache as well. This avoids us
166 # having to regenerate the method_map.
168 $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
171 ## Metaclass compatibility
173 my %base_metaclass = (
174 attribute_metaclass => 'Class::MOP::Attribute',
175 method_metaclass => 'Class::MOP::Method',
176 wrapped_method_metaclass => 'Class::MOP::Method::Wrapped',
177 instance_metaclass => 'Class::MOP::Instance',
178 constructor_class => 'Class::MOP::Method::Constructor',
179 destructor_class => 'Class::MOP::Method::Destructor',
182 sub _base_metaclasses { %base_metaclass }
185 sub _check_metaclass_compatibility {
188 if (my @superclasses = $self->superclasses) {
189 $self->_fix_metaclass_incompatibility(@superclasses);
191 my %base_metaclass = $self->_base_metaclasses;
193 # this is always okay ...
194 return if ref($self) eq 'Class::MOP::Class'
196 my $meta = $self->$_;
197 !defined($meta) || $meta eq $base_metaclass{$_}
198 } keys %base_metaclass;
200 for my $superclass (@superclasses) {
201 $self->_check_class_metaclass_compatibility($superclass);
204 for my $metaclass_type (keys %base_metaclass) {
205 next unless defined $self->$metaclass_type;
206 for my $superclass (@superclasses) {
207 $self->_check_single_metaclass_compatibility(
208 $metaclass_type, $superclass
215 sub _class_metaclass_is_compatible {
217 my ( $superclass_name ) = @_;
219 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
223 # we need to deal with the possibility
224 # of class immutability here, and then
225 # get the name of the class appropriately
227 = $super_meta->is_immutable
228 ? $super_meta->_get_mutable_metaclass_name()
231 return $self->isa($super_meta_type);
234 sub _check_class_metaclass_compatibility {
236 my ( $superclass_name ) = @_;
238 if (!$self->_class_metaclass_is_compatible($superclass_name)) {
239 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
242 # we need to deal with the possibility
243 # of class immutability here, and then
244 # get the name of the class appropriately
246 = $super_meta->is_immutable
247 ? $super_meta->_get_mutable_metaclass_name()
250 confess "The metaclass of " . $self->name . " ("
251 . (ref($self)) . ")" . " is not compatible with "
252 . "the metaclass of its superclass, "
253 . $superclass_name . " (" . ($super_meta_type) . ")";
257 sub _single_metaclass_is_compatible {
259 my ( $metaclass_type, $superclass_name ) = @_;
261 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
264 # for instance, Moose::Meta::Class has a error_class attribute, but
265 # Class::MOP::Class doesn't - this shouldn't be an error
266 return 1 unless $super_meta->can($metaclass_type);
267 # for instance, Moose::Meta::Class has a destructor_class, but
268 # Class::MOP::Class doesn't - this shouldn't be an error
269 return 1 if defined $self->$metaclass_type
270 && !defined $super_meta->$metaclass_type;
272 return $self->$metaclass_type->isa($super_meta->$metaclass_type);
275 sub _check_single_metaclass_compatibility {
277 my ( $metaclass_type, $superclass_name ) = @_;
279 if (!$self->_single_metaclass_is_compatible($metaclass_type, $superclass_name)) {
280 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
281 my $metaclass_type_name = $metaclass_type;
282 $metaclass_type_name =~ s/_(?:meta)?class$//;
283 $metaclass_type_name =~ s/_/ /g;
284 confess "The $metaclass_type_name metaclass for "
285 . $self->name . " (" . ($self->$metaclass_type)
286 . ")" . " is not compatible with the "
287 . "$metaclass_type_name metaclass of its "
288 . "superclass, " . $superclass_name . " ("
289 . ($super_meta->$metaclass_type) . ")";
293 sub _can_fix_class_metaclass_incompatibility_by_subclassing {
295 my ($super_meta) = @_;
298 # we need to deal with the possibility
299 # of class immutability here, and then
300 # get the name of the class appropriately
302 = $super_meta->is_immutable
303 ? $super_meta->_get_mutable_metaclass_name()
306 return $super_meta_type ne blessed($self)
307 && $super_meta->isa(blessed($self));
310 sub _can_fix_single_metaclass_incompatibility_by_subclassing {
312 my ($metaclass_type, $super_meta) = @_;
314 my $specific_meta = $self->$metaclass_type;
315 return unless $super_meta->can($metaclass_type);
316 my $super_specific_meta = $super_meta->$metaclass_type;
318 # for instance, Moose::Meta::Class has a destructor_class, but
319 # Class::MOP::Class doesn't - this shouldn't be an error
320 return if defined $specific_meta
321 && !defined $super_specific_meta;
323 return $specific_meta ne $super_specific_meta
324 && $super_specific_meta->isa($specific_meta);
327 sub _can_fix_metaclass_incompatibility_by_subclassing {
329 my ($super_meta) = @_;
331 return 1 if $self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta);
333 my %base_metaclass = $self->_base_metaclasses;
334 for my $metaclass_type (keys %base_metaclass) {
335 next unless defined $self->$metaclass_type;
336 return 1 if $self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta);
342 sub _can_fix_metaclass_incompatibility {
344 return $self->_can_fix_metaclass_incompatibility_by_subclassing(@_);
347 sub _fix_metaclass_incompatibility {
352 for my $super (map { Class::MOP::Class->initialize($_) } @supers) {
354 if $self->_can_fix_metaclass_incompatibility($super);
356 return unless $necessary;
358 for my $super (map { Class::MOP::Class->initialize($_) } @supers) {
359 if (!$self->_class_metaclass_is_compatible($super->name)) {
360 $self->_fix_class_metaclass_incompatibility($super);
364 my %base_metaclass = $self->_base_metaclasses;
365 for my $metaclass_type (keys %base_metaclass) {
366 next unless defined $self->$metaclass_type;
367 for my $super (map { Class::MOP::Class->initialize($_) } @supers) {
368 if (!$self->_single_metaclass_is_compatible($metaclass_type, $super->name)) {
369 $self->_fix_single_metaclass_incompatibility(
370 $metaclass_type, $super
377 sub _fix_class_metaclass_incompatibility {
379 my ( $super_meta ) = @_;
381 if ($self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta)) {
383 || confess "Can't fix metaclass incompatibility for "
385 . " because it is not pristine.";
387 my $super_meta_name = $super_meta->is_immutable
388 ? $super_meta->_get_mutable_metaclass_name
389 : blessed($super_meta);
390 $super_meta_name->meta->rebless_instance($self);
394 sub _fix_single_metaclass_incompatibility {
396 my ( $metaclass_type, $super_meta ) = @_;
398 if ($self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta)) {
400 || confess "Can't fix metaclass incompatibility for "
402 . " because it is not pristine.";
404 $self->{$metaclass_type} = $super_meta->$metaclass_type;
412 # this should be sufficient, if you have a
413 # use case where it is not, write a test and
415 my $ANON_CLASS_SERIAL = 0;
418 # we need a sufficiently annoying prefix
419 # this should suffice for now, this is
420 # used in a couple of places below, so
421 # need to put it up here for now.
422 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
426 no warnings 'uninitialized';
427 $self->name =~ /^$ANON_CLASS_PREFIX/o;
430 sub create_anon_class {
431 my ($class, %options) = @_;
432 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
433 return $class->create($package_name, %options);
437 # this will only get called for
438 # anon-classes, all other calls
439 # are assumed to occur during
440 # global destruction and so don't
441 # really need to be handled explicitly
445 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
447 no warnings 'uninitialized';
448 my $name = $self->name;
449 return unless $name =~ /^$ANON_CLASS_PREFIX/o;
451 # Moose does a weird thing where it replaces the metaclass for
452 # class when fixing metaclass incompatibility. In that case,
453 # we don't want to clean out the namespace now. We can detect
454 # that because Moose will explicitly update the singleton
455 # cache in Class::MOP.
456 my $current_meta = Class::MOP::get_metaclass_by_name($name);
457 return if $current_meta ne $self;
459 my ($serial_id) = ($name =~ /^$ANON_CLASS_PREFIX(\d+)/o);
461 @{$name . '::ISA'} = ();
462 %{$name . '::'} = ();
463 delete ${$ANON_CLASS_PREFIX}{$serial_id . '::'};
465 Class::MOP::remove_metaclass_by_name($name);
470 # creating classes with MOP ...
473 my ( $class, @args ) = @_;
475 unshift @args, 'package' if @args % 2 == 1;
477 my (%options) = @args;
478 my $package_name = $options{package};
480 (ref $options{superclasses} eq 'ARRAY')
481 || confess "You must pass an ARRAY ref of superclasses"
482 if exists $options{superclasses};
484 (ref $options{attributes} eq 'ARRAY')
485 || confess "You must pass an ARRAY ref of attributes"
486 if exists $options{attributes};
488 (ref $options{methods} eq 'HASH')
489 || confess "You must pass a HASH ref of methods"
490 if exists $options{methods};
492 my (%initialize_options) = @args;
493 delete @initialize_options{qw(
501 my $meta = $class->initialize( $package_name => %initialize_options );
503 $meta->_instantiate_module( $options{version}, $options{authority} );
506 $meta->add_method('meta' => sub {
507 $class->initialize(ref($_[0]) || $_[0]);
510 $meta->superclasses(@{$options{superclasses}})
511 if exists $options{superclasses};
513 # process attributes first, so that they can
514 # install accessors, but locally defined methods
515 # can then overwrite them. It is maybe a little odd, but
516 # I think this should be the order of things.
517 if (exists $options{attributes}) {
518 foreach my $attr (@{$options{attributes}}) {
519 $meta->add_attribute($attr);
522 if (exists $options{methods}) {
523 foreach my $method_name (keys %{$options{methods}}) {
524 $meta->add_method($method_name, $options{methods}->{$method_name});
533 # all these attribute readers will be bootstrapped
534 # away in the Class::MOP bootstrap section
536 sub instance_metaclass { $_[0]->{'instance_metaclass'} }
537 sub immutable_trait { $_[0]->{'immutable_trait'} }
538 sub constructor_class { $_[0]->{'constructor_class'} }
539 sub constructor_name { $_[0]->{'constructor_name'} }
540 sub destructor_class { $_[0]->{'destructor_class'} }
542 # Instance Construction & Cloning
548 # we need to protect the integrity of the
549 # Class::MOP::Class singletons here, so we
550 # delegate this to &construct_class_instance
551 # which will deal with the singletons
552 return $class->_construct_class_instance(@_)
553 if $class->name->isa('Class::MOP::Class');
554 return $class->_construct_instance(@_);
557 sub _construct_instance {
559 my $params = @_ == 1 ? $_[0] : {@_};
560 my $meta_instance = $class->get_meta_instance();
562 # the code below is almost certainly incorrect
563 # but this is foreign inheritance, so we might
564 # have to kludge it in the end.
566 if (my $instance_class = blessed($params->{__INSTANCE__})) {
567 ($instance_class eq $class->name)
568 || confess "Objects passed as the __INSTANCE__ parameter must "
569 . "already be blessed into the correct class, but "
570 . "$params->{__INSTANCE__} is not a " . $class->name;
571 $instance = $params->{__INSTANCE__};
573 elsif (exists $params->{__INSTANCE__}) {
574 confess "The __INSTANCE__ parameter must be a blessed reference, not "
575 . $params->{__INSTANCE__};
578 $instance = $meta_instance->create_instance();
580 foreach my $attr ($class->get_all_attributes()) {
581 $attr->initialize_instance_slot($meta_instance, $instance, $params);
584 # this will only work for a HASH instance type
585 if ($class->is_anon_class) {
586 (reftype($instance) eq 'HASH')
587 || confess "Currently only HASH based instances are supported with instance of anon-classes";
589 # At some point we should make this official
590 # as a reserved slot name, but right now I am
591 # going to keep it here.
592 # my $RESERVED_MOP_SLOT = '__MOP__';
593 $instance->{'__MOP__'} = $class;
599 sub get_meta_instance {
601 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
604 sub _create_meta_instance {
607 my $instance = $self->instance_metaclass->new(
608 associated_metaclass => $self,
609 attributes => [ $self->get_all_attributes() ],
612 $self->add_meta_instance_dependencies()
613 if $instance->is_dependent_on_superclasses();
620 my $instance = shift;
621 (blessed($instance) && $instance->isa($class->name))
622 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
625 # we need to protect the integrity of the
626 # Class::MOP::Class singletons here, they
627 # should not be cloned.
628 return $instance if $instance->isa('Class::MOP::Class');
629 $class->_clone_instance($instance, @_);
632 sub _clone_instance {
633 my ($class, $instance, %params) = @_;
635 || confess "You can only clone instances, ($instance) is not a blessed instance";
636 my $meta_instance = $class->get_meta_instance();
637 my $clone = $meta_instance->clone_instance($instance);
638 foreach my $attr ($class->get_all_attributes()) {
639 if ( defined( my $init_arg = $attr->init_arg ) ) {
640 if (exists $params{$init_arg}) {
641 $attr->set_value($clone, $params{$init_arg});
648 sub rebless_instance {
649 my ($self, $instance, %params) = @_;
651 my $old_metaclass = Class::MOP::class_of($instance);
653 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
654 $self->name->isa($old_class)
655 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
657 $old_metaclass->rebless_instance_away($instance, $self, %params)
660 my $meta_instance = $self->get_meta_instance();
663 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
664 $meta_instance->rebless_instance_structure($_[1], $self);
666 foreach my $attr ( $self->get_all_attributes ) {
667 if ( $attr->has_value($instance) ) {
668 if ( defined( my $init_arg = $attr->init_arg ) ) {
669 $params{$init_arg} = $attr->get_value($instance)
670 unless exists $params{$init_arg};
673 $attr->set_value($instance, $attr->get_value($instance));
678 foreach my $attr ($self->get_all_attributes) {
679 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
685 sub rebless_instance_back {
686 my ( $self, $instance ) = @_;
688 my $old_metaclass = Class::MOP::class_of($instance);
691 = $old_metaclass ? $old_metaclass->name : blessed($instance);
692 $old_class->isa( $self->name )
694 "You may rebless only into a superclass of ($old_class), of which ("
698 $old_metaclass->rebless_instance_away( $instance, $self )
701 my $meta_instance = $self->get_meta_instance;
703 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
704 $meta_instance->rebless_instance_structure( $_[1], $self );
706 for my $attr ( $old_metaclass->get_all_attributes ) {
707 next if $self->has_attribute( $attr->name );
708 $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
714 sub rebless_instance_away {
715 # this intentionally does nothing, it is just a hook
718 sub _attach_attribute {
719 my ($self, $attribute) = @_;
720 $attribute->attach_to_class($self);
723 sub _post_add_attribute {
724 my ( $self, $attribute ) = @_;
726 $self->invalidate_meta_instances;
728 # invalidate package flag here
731 $attribute->install_accessors;
734 $self->remove_attribute( $attribute->name );
739 sub remove_attribute {
742 my $removed_attribute = $self->SUPER::remove_attribute(@_)
745 $self->invalidate_meta_instances;
747 $removed_attribute->remove_accessors;
748 $removed_attribute->detach_from_class;
750 return$removed_attribute;
753 sub find_attribute_by_name {
754 my ( $self, $attr_name ) = @_;
756 foreach my $class ( $self->linearized_isa ) {
757 # fetch the meta-class ...
758 my $meta = Class::MOP::Class->initialize($class);
759 return $meta->get_attribute($attr_name)
760 if $meta->has_attribute($attr_name);
766 sub get_all_attributes {
768 my %attrs = map { %{ Class::MOP::Class->initialize($_)->_attribute_map } }
769 reverse $self->linearized_isa;
770 return values %attrs;
777 my $var_spec = { sigil => '@', type => 'ARRAY', name => 'ISA' };
780 @{$self->get_package_symbol($var_spec)} = @supers;
783 # on 5.8 and below, we need to call
784 # a method to get Perl to detect
785 # a cycle in the class hierarchy
786 my $class = $self->name;
790 # we need to check the metaclass
791 # compatibility here so that we can
792 # be sure that the superclass is
793 # not potentially creating an issues
794 # we don't know about
796 $self->_check_metaclass_compatibility();
797 $self->_superclasses_updated();
799 @{$self->get_package_symbol($var_spec)};
802 sub _superclasses_updated {
804 $self->update_meta_instance_dependencies();
809 my $super_class = $self->name;
811 return @{ $super_class->mro::get_isarev() };
814 sub direct_subclasses {
816 my $super_class = $self->name;
821 } Class::MOP::Class->initialize($_)->superclasses
826 return @{ mro::get_linear_isa( (shift)->name ) };
829 sub class_precedence_list {
831 my $name = $self->name;
833 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
835 # We need to check for circular inheritance here
836 # if we are are not on 5.10, cause 5.8 detects it
837 # late. This will do nothing if all is well, and
838 # blow up otherwise. Yes, it's an ugly hack, better
839 # suggestions are welcome.
841 ($name || return)->isa('This is a test for circular inheritance')
844 # if our mro is c3, we can
845 # just grab the linear_isa
846 if (mro::get_mro($name) eq 'c3') {
847 return @{ mro::get_linear_isa($name) }
851 # we can't grab the linear_isa for dfs
852 # since it has all the duplicates
857 Class::MOP::Class->initialize($_)->class_precedence_list()
858 } $self->superclasses()
866 my $fetch_and_prepare_method = sub {
867 my ($self, $method_name) = @_;
868 my $wrapped_metaclass = $self->wrapped_method_metaclass;
870 my $method = $self->get_method($method_name);
871 # if we dont have local ...
873 # try to find the next method
874 $method = $self->find_next_method_by_name($method_name);
875 # die if it does not exist
877 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
878 # and now make sure to wrap it
879 # even if it is already wrapped
880 # because we need a new sub ref
881 $method = $wrapped_metaclass->wrap($method,
882 package_name => $self->name,
883 name => $method_name,
887 # now make sure we wrap it properly
888 $method = $wrapped_metaclass->wrap($method,
889 package_name => $self->name,
890 name => $method_name,
891 ) unless $method->isa($wrapped_metaclass);
893 $self->add_method($method_name => $method);
897 sub add_before_method_modifier {
898 my ($self, $method_name, $method_modifier) = @_;
899 (defined $method_name && length $method_name)
900 || confess "You must pass in a method name";
901 my $method = $fetch_and_prepare_method->($self, $method_name);
902 $method->add_before_modifier(
903 subname(':before' => $method_modifier)
907 sub add_after_method_modifier {
908 my ($self, $method_name, $method_modifier) = @_;
909 (defined $method_name && length $method_name)
910 || confess "You must pass in a method name";
911 my $method = $fetch_and_prepare_method->($self, $method_name);
912 $method->add_after_modifier(
913 subname(':after' => $method_modifier)
917 sub add_around_method_modifier {
918 my ($self, $method_name, $method_modifier) = @_;
919 (defined $method_name && length $method_name)
920 || confess "You must pass in a method name";
921 my $method = $fetch_and_prepare_method->($self, $method_name);
922 $method->add_around_modifier(
923 subname(':around' => $method_modifier)
928 # the methods above used to be named like this:
929 # ${pkg}::${method}:(before|after|around)
930 # but this proved problematic when using one modifier
931 # to wrap multiple methods (something which is likely
932 # to happen pretty regularly IMO). So instead of naming
933 # it like this, I have chosen to just name them purely
934 # with their modifier names, like so:
935 # :(before|after|around)
936 # The fact is that in a stack trace, it will be fairly
937 # evident from the context what method they are attached
938 # to, and so don't need the fully qualified name.
941 sub find_method_by_name {
942 my ($self, $method_name) = @_;
943 (defined $method_name && length $method_name)
944 || confess "You must define a method name to find";
945 foreach my $class ($self->linearized_isa) {
946 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
947 return $method if defined $method;
952 sub get_all_methods {
956 for my $class ( reverse $self->linearized_isa ) {
957 my $meta = Class::MOP::Class->initialize($class);
959 $methods{$_} = $meta->get_method($_)
960 for $meta->get_method_list;
963 return values %methods;
966 sub get_all_method_names {
969 return grep { !$uniq{$_}++ } map { Class::MOP::Class->initialize($_)->get_method_list } $self->linearized_isa;
972 sub find_all_methods_by_name {
973 my ($self, $method_name) = @_;
974 (defined $method_name && length $method_name)
975 || confess "You must define a method name to find";
977 foreach my $class ($self->linearized_isa) {
978 # fetch the meta-class ...
979 my $meta = Class::MOP::Class->initialize($class);
981 name => $method_name,
983 code => $meta->get_method($method_name)
984 } if $meta->has_method($method_name);
989 sub find_next_method_by_name {
990 my ($self, $method_name) = @_;
991 (defined $method_name && length $method_name)
992 || confess "You must define a method name to find";
993 my @cpl = $self->linearized_isa;
994 shift @cpl; # discard ourselves
995 foreach my $class (@cpl) {
996 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
997 return $method if defined $method;
1002 sub update_meta_instance_dependencies {
1005 if ( $self->{meta_instance_dependencies} ) {
1006 return $self->add_meta_instance_dependencies;
1010 sub add_meta_instance_dependencies {
1013 $self->remove_meta_instance_dependencies;
1015 my @attrs = $self->get_all_attributes();
1018 my @classes = grep { not $seen{ $_->name }++ }
1019 map { $_->associated_class } @attrs;
1021 foreach my $class (@classes) {
1022 $class->add_dependent_meta_instance($self);
1025 $self->{meta_instance_dependencies} = \@classes;
1028 sub remove_meta_instance_dependencies {
1031 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
1032 foreach my $class (@$classes) {
1033 $class->remove_dependent_meta_instance($self);
1043 sub add_dependent_meta_instance {
1044 my ( $self, $metaclass ) = @_;
1045 push @{ $self->{dependent_meta_instances} }, $metaclass;
1048 sub remove_dependent_meta_instance {
1049 my ( $self, $metaclass ) = @_;
1050 my $name = $metaclass->name;
1051 @$_ = grep { $_->name ne $name } @$_
1052 for $self->{dependent_meta_instances};
1055 sub invalidate_meta_instances {
1057 $_->invalidate_meta_instance()
1058 for $self, @{ $self->{dependent_meta_instances} };
1061 sub invalidate_meta_instance {
1063 undef $self->{_meta_instance};
1066 # check if we can reinitialize
1070 # if any local attr is defined
1071 return if $self->get_attribute_list;
1073 # or any non-declared methods
1074 for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1075 return if $method->isa("Class::MOP::Method::Generated");
1076 # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1084 sub is_mutable { 1 }
1085 sub is_immutable { 0 }
1087 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1089 sub _immutable_options {
1090 my ( $self, @args ) = @_;
1093 inline_accessors => 1,
1094 inline_constructor => 1,
1095 inline_destructor => 0,
1097 immutable_trait => $self->immutable_trait,
1098 constructor_name => $self->constructor_name,
1099 constructor_class => $self->constructor_class,
1100 destructor_class => $self->destructor_class,
1105 sub make_immutable {
1106 my ( $self, @args ) = @_;
1108 if ( $self->is_mutable ) {
1109 $self->_initialize_immutable( $self->_immutable_options(@args) );
1110 $self->_rebless_as_immutable(@args);
1121 if ( $self->is_immutable ) {
1122 my @args = $self->immutable_options;
1123 $self->_rebless_as_mutable();
1124 $self->_remove_inlined_code(@args);
1125 delete $self->{__immutable};
1133 sub _rebless_as_immutable {
1134 my ( $self, @args ) = @_;
1136 $self->{__immutable}{original_class} = ref $self;
1138 bless $self => $self->_immutable_metaclass(@args);
1141 sub _immutable_metaclass {
1142 my ( $self, %args ) = @_;
1144 if ( my $class = $args{immutable_metaclass} ) {
1148 my $trait = $args{immutable_trait} = $self->immutable_trait
1149 || confess "no immutable trait specified for $self";
1151 my $meta = $self->meta;
1152 my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1156 if ( $meta_attr and $trait eq $meta_attr->default ) {
1157 # if the trait is the same as the default we try and pick a
1158 # predictable name for the immutable metaclass
1159 $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1162 $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1163 $trait, 'ForMetaClass', ref($self);
1167 if Class::MOP::is_class_loaded($class_name);
1169 # If the metaclass is a subclass of CMOP::Class which has had
1170 # metaclass roles applied (via Moose), then we want to make sure
1171 # that we preserve that anonymous class (see Fey::ORM for an
1172 # example of where this matters).
1174 = $meta->is_immutable
1175 ? $meta->_get_mutable_metaclass_name
1178 my $immutable_meta = $meta_name->create(
1180 superclasses => [ ref $self ],
1183 Class::MOP::load_class($trait);
1184 for my $meth ( Class::MOP::Class->initialize($trait)->get_all_methods ) {
1185 my $meth_name = $meth->name;
1187 if ( $immutable_meta->find_method_by_name( $meth_name ) ) {
1188 $immutable_meta->add_around_method_modifier( $meth_name, $meth->body );
1191 $immutable_meta->add_method( $meth_name, $meth->clone );
1195 $immutable_meta->make_immutable(
1196 inline_constructor => 0,
1197 inline_accessors => 0,
1203 sub _remove_inlined_code {
1206 $self->remove_method( $_->name ) for $self->_inlined_methods;
1208 delete $self->{__immutable}{inlined_methods};
1211 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1213 sub _add_inlined_method {
1214 my ( $self, $method ) = @_;
1216 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1219 sub _initialize_immutable {
1220 my ( $self, %args ) = @_;
1222 $self->{__immutable}{options} = \%args;
1223 $self->_install_inlined_code(%args);
1226 sub _install_inlined_code {
1227 my ( $self, %args ) = @_;
1230 $self->_inline_accessors(%args) if $args{inline_accessors};
1231 $self->_inline_constructor(%args) if $args{inline_constructor};
1232 $self->_inline_destructor(%args) if $args{inline_destructor};
1235 sub _rebless_as_mutable {
1238 bless $self, $self->_get_mutable_metaclass_name;
1243 sub _inline_accessors {
1246 foreach my $attr_name ( $self->get_attribute_list ) {
1247 $self->get_attribute($attr_name)->install_accessors(1);
1251 sub _inline_constructor {
1252 my ( $self, %args ) = @_;
1254 my $name = $args{constructor_name};
1255 # A class may not even have a constructor, and that's okay.
1256 return unless defined $name;
1258 if ( $self->has_method($name) && !$args{replace_constructor} ) {
1259 my $class = $self->name;
1260 warn "Not inlining a constructor for $class since it defines"
1261 . " its own constructor.\n"
1262 . "If you are certain you don't need to inline your"
1263 . " constructor, specify inline_constructor => 0 in your"
1264 . " call to $class->meta->make_immutable\n";
1268 my $constructor_class = $args{constructor_class};
1270 Class::MOP::load_class($constructor_class);
1272 my $constructor = $constructor_class->new(
1276 package_name => $self->name,
1280 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1281 $self->add_method( $name => $constructor );
1282 $self->_add_inlined_method($constructor);
1286 sub _inline_destructor {
1287 my ( $self, %args ) = @_;
1289 ( exists $args{destructor_class} && defined $args{destructor_class} )
1290 || confess "The 'inline_destructor' option is present, but "
1291 . "no destructor class was specified";
1293 if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1294 my $class = $self->name;
1295 warn "Not inlining a destructor for $class since it defines"
1296 . " its own destructor.\n";
1300 my $destructor_class = $args{destructor_class};
1302 Class::MOP::load_class($destructor_class);
1304 return unless $destructor_class->is_needed($self);
1306 my $destructor = $destructor_class->new(
1309 package_name => $self->name,
1313 if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1314 $self->add_method( 'DESTROY' => $destructor );
1315 $self->_add_inlined_method($destructor);
1327 Class::MOP::Class - Class Meta Object
1331 # assuming that class Foo
1332 # has been defined, you can
1334 # use this for introspection ...
1336 # add a method to Foo ...
1337 Foo->meta->add_method( 'bar' => sub {...} )
1339 # get a list of all the classes searched
1340 # the method dispatcher in the correct order
1341 Foo->meta->class_precedence_list()
1343 # remove a method from Foo
1344 Foo->meta->remove_method('bar');
1346 # or use this to actually create classes ...
1348 Class::MOP::Class->create(
1351 superclasses => ['Foo'],
1353 Class::MOP::Attribute->new('$bar'),
1354 Class::MOP::Attribute->new('$baz'),
1357 calculate_bar => sub {...},
1358 construct_baz => sub {...}
1365 The Class Protocol is the largest and most complex part of the
1366 Class::MOP meta-object protocol. It controls the introspection and
1367 manipulation of Perl 5 classes, and it can create them as well. The
1368 best way to understand what this module can do is to read the
1369 documentation for each of its methods.
1373 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1377 =head2 Class construction
1379 These methods all create new C<Class::MOP::Class> objects. These
1380 objects can represent existing classes or they can be used to create
1381 new classes from scratch.
1383 The metaclass object for a given class is a singleton. If you attempt
1384 to create a metaclass for the same class twice, you will just get the
1389 =item B<< Class::MOP::Class->create($package_name, %options) >>
1391 This method creates a new C<Class::MOP::Class> object with the given
1392 package name. It accepts a number of options:
1398 An optional version number for the newly created package.
1402 An optional authority for the newly created package.
1404 =item * superclasses
1406 An optional array reference of superclass names.
1410 An optional hash reference of methods for the class. The keys of the
1411 hash reference are method names and values are subroutine references.
1415 An optional array reference of L<Class::MOP::Attribute> objects.
1419 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1421 This method works just like C<< Class::MOP::Class->create >> but it
1422 creates an "anonymous" class. In fact, the class does have a name, but
1423 that name is a unique name generated internally by this module.
1425 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1426 parameters that C<create> accepts.
1428 Anonymous classes are destroyed once the metaclass they are attached
1429 to goes out of scope, and will be removed from Perl's internal symbol
1432 All instances of an anonymous class keep a special reference to the
1433 metaclass object, which prevents the metaclass from going out of scope
1434 while any instances exist.
1436 This only works if the instance is based on a hash reference, however.
1438 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1440 This method will initialize a C<Class::MOP::Class> object for the
1441 named package. Unlike C<create>, this method I<will not> create a new
1444 The purpose of this method is to retrieve a C<Class::MOP::Class>
1445 object for introspecting an existing class.
1447 If an existing C<Class::MOP::Class> object exists for the named
1448 package, it will be returned, and any options provided will be
1451 If the object does not yet exist, it will be created.
1453 The valid options that can be passed to this method are
1454 C<attribute_metaclass>, C<method_metaclass>,
1455 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1456 optional, and default to the appropriate class in the C<Class::MOP>
1461 =head2 Object instance construction and cloning
1463 These methods are all related to creating and/or cloning object
1468 =item B<< $metaclass->clone_object($instance, %params) >>
1470 This method clones an existing object instance. Any parameters you
1471 provide are will override existing attribute values in the object.
1473 This is a convenience method for cloning an object instance, then
1474 blessing it into the appropriate package.
1476 You could implement a clone method in your class, using this method:
1479 my ($self, %params) = @_;
1480 $self->meta->clone_object($self, %params);
1483 =item B<< $metaclass->rebless_instance($instance, %params) >>
1485 This method changes the class of C<$instance> to the metaclass's class.
1487 You can only rebless an instance into a subclass of its current
1488 class. If you pass any additional parameters, these will be treated
1489 like constructor parameters and used to initialize the object's
1490 attributes. Any existing attributes that are already set will be
1493 Before reblessing the instance, this method will call
1494 C<rebless_instance_away> on the instance's current metaclass. This method
1495 will be passed the instance, the new metaclass, and any parameters
1496 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1497 does nothing; it is merely a hook.
1499 =item B<< $metaclass->rebless_instance_back($instance) >>
1501 Does the same thing as C<rebless_instance>, except that you can only
1502 rebless an instance into one of its superclasses. Any attributes that
1503 do not exist in the superclass will be deinitialized.
1505 This is a much more dangerous operation than C<rebless_instance>,
1506 especially when multiple inheritance is involved, so use this carefully!
1508 =item B<< $metaclass->new_object(%params) >>
1510 This method is used to create a new object of the metaclass's
1511 class. Any parameters you provide are used to initialize the
1512 instance's attributes. A special C<__INSTANCE__> key can be passed to
1513 provide an already generated instance, rather than having Class::MOP
1514 generate it for you. This is mostly useful for using Class::MOP with
1515 foreign classes which generate instances using their own constructors.
1517 =item B<< $metaclass->instance_metaclass >>
1519 Returns the class name of the instance metaclass. See
1520 L<Class::MOP::Instance> for more information on the instance
1523 =item B<< $metaclass->get_meta_instance >>
1525 Returns an instance of the C<instance_metaclass> to be used in the
1526 construction of a new instance of the class.
1530 =head2 Informational predicates
1532 These are a few predicate methods for asking information about the
1537 =item B<< $metaclass->is_anon_class >>
1539 This returns true if the class was created by calling C<<
1540 Class::MOP::Class->create_anon_class >>.
1542 =item B<< $metaclass->is_mutable >>
1544 This returns true if the class is still mutable.
1546 =item B<< $metaclass->is_immutable >>
1548 This returns true if the class has been made immutable.
1550 =item B<< $metaclass->is_pristine >>
1552 A class is I<not> pristine if it has non-inherited attributes or if it
1553 has any generated methods.
1557 =head2 Inheritance Relationships
1561 =item B<< $metaclass->superclasses(@superclasses) >>
1563 This is a read-write accessor which represents the superclass
1564 relationships of the metaclass's class.
1566 This is basically sugar around getting and setting C<@ISA>.
1568 =item B<< $metaclass->class_precedence_list >>
1570 This returns a list of all of the class's ancestor classes. The
1571 classes are returned in method dispatch order.
1573 =item B<< $metaclass->linearized_isa >>
1575 This returns a list based on C<class_precedence_list> but with all
1578 =item B<< $metaclass->subclasses >>
1580 This returns a list of all subclasses for this class, even indirect
1583 =item B<< $metaclass->direct_subclasses >>
1585 This returns a list of immediate subclasses for this class, which does not
1586 include indirect subclasses.
1590 =head2 Method introspection and creation
1592 These methods allow you to introspect a class's methods, as well as
1593 add, remove, or change methods.
1595 Determining what is truly a method in a Perl 5 class requires some
1596 heuristics (aka guessing).
1598 Methods defined outside the package with a fully qualified name (C<sub
1599 Package::name { ... }>) will be included. Similarly, methods named
1600 with a fully qualified name using L<Sub::Name> are also included.
1602 However, we attempt to ignore imported functions.
1604 Ultimately, we are using heuristics to determine what truly is a
1605 method in a class, and these heuristics may get the wrong answer in
1606 some edge cases. However, for most "normal" cases the heuristics work
1611 =item B<< $metaclass->get_method($method_name) >>
1613 This will return a L<Class::MOP::Method> for the specified
1614 C<$method_name>. If the class does not have the specified method, it
1617 =item B<< $metaclass->has_method($method_name) >>
1619 Returns a boolean indicating whether or not the class defines the
1620 named method. It does not include methods inherited from parent
1623 =item B<< $metaclass->get_method_list >>
1625 This will return a list of method I<names> for all methods defined in
1628 =item B<< $metaclass->add_method($method_name, $method) >>
1630 This method takes a method name and a subroutine reference, and adds
1631 the method to the class.
1633 The subroutine reference can be a L<Class::MOP::Method>, and you are
1634 strongly encouraged to pass a meta method object instead of a code
1635 reference. If you do so, that object gets stored as part of the
1636 class's method map directly. If not, the meta information will have to
1637 be recreated later, and may be incorrect.
1639 If you provide a method object, this method will clone that object if
1640 the object's package name does not match the class name. This lets us
1641 track the original source of any methods added from other classes
1642 (notably Moose roles).
1644 =item B<< $metaclass->remove_method($method_name) >>
1646 Remove the named method from the class. This method returns the
1647 L<Class::MOP::Method> object for the method.
1649 =item B<< $metaclass->method_metaclass >>
1651 Returns the class name of the method metaclass, see
1652 L<Class::MOP::Method> for more information on the method metaclass.
1654 =item B<< $metaclass->wrapped_method_metaclass >>
1656 Returns the class name of the wrapped method metaclass, see
1657 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1660 =item B<< $metaclass->get_all_methods >>
1662 This will traverse the inheritance hierarchy and return a list of all
1663 the L<Class::MOP::Method> objects for this class and its parents.
1665 =item B<< $metaclass->find_method_by_name($method_name) >>
1667 This will return a L<Class::MOP::Method> for the specified
1668 C<$method_name>. If the class does not have the specified method, it
1671 Unlike C<get_method>, this method I<will> look for the named method in
1674 =item B<< $metaclass->get_all_method_names >>
1676 This will return a list of method I<names> for all of this class's
1677 methods, including inherited methods.
1679 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1681 This method looks for the named method in the class and all of its
1682 parents. It returns every matching method it finds in the inheritance
1683 tree, so it returns a list of methods.
1685 Each method is returned as a hash reference with three keys. The keys
1686 are C<name>, C<class>, and C<code>. The C<code> key has a
1687 L<Class::MOP::Method> object as its value.
1689 The list of methods is distinct.
1691 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1693 This method returns the first method in any superclass matching the
1694 given name. It is effectively the method that C<SUPER::$method_name>
1699 =head2 Attribute introspection and creation
1701 Because Perl 5 does not have a core concept of attributes in classes,
1702 we can only return information about attributes which have been added
1703 via this class's methods. We cannot discover information about
1704 attributes which are defined in terms of "regular" Perl 5 methods.
1708 =item B<< $metaclass->get_attribute($attribute_name) >>
1710 This will return a L<Class::MOP::Attribute> for the specified
1711 C<$attribute_name>. If the class does not have the specified
1712 attribute, it returns C<undef>.
1714 NOTE that get_attribute does not search superclasses, for that you
1715 need to use C<find_attribute_by_name>.
1717 =item B<< $metaclass->has_attribute($attribute_name) >>
1719 Returns a boolean indicating whether or not the class defines the
1720 named attribute. It does not include attributes inherited from parent
1723 =item B<< $metaclass->get_attribute_list >>
1725 This will return a list of attributes I<names> for all attributes
1726 defined in this class.
1728 =item B<< $metaclass->get_all_attributes >>
1730 This will traverse the inheritance hierarchy and return a list of all
1731 the L<Class::MOP::Attribute> objects for this class and its parents.
1733 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1735 This will return a L<Class::MOP::Attribute> for the specified
1736 C<$attribute_name>. If the class does not have the specified
1737 attribute, it returns C<undef>.
1739 Unlike C<get_attribute>, this attribute I<will> look for the named
1740 attribute in superclasses.
1742 =item B<< $metaclass->add_attribute(...) >>
1744 This method accepts either an existing L<Class::MOP::Attribute>
1745 object or parameters suitable for passing to that class's C<new>
1748 The attribute provided will be added to the class.
1750 Any accessor methods defined by the attribute will be added to the
1751 class when the attribute is added.
1753 If an attribute of the same name already exists, the old attribute
1754 will be removed first.
1756 =item B<< $metaclass->remove_attribute($attribute_name) >>
1758 This will remove the named attribute from the class, and
1759 L<Class::MOP::Attribute> object.
1761 Removing an attribute also removes any accessor methods defined by the
1764 However, note that removing an attribute will only affect I<future>
1765 object instances created for this class, not existing instances.
1767 =item B<< $metaclass->attribute_metaclass >>
1769 Returns the class name of the attribute metaclass for this class. By
1770 default, this is L<Class::MOP::Attribute>.
1774 =head2 Class Immutability
1776 Making a class immutable "freezes" the class definition. You can no
1777 longer call methods which alter the class, such as adding or removing
1778 methods or attributes.
1780 Making a class immutable lets us optimize the class by inlining some
1781 methods, and also allows us to optimize some methods on the metaclass
1784 After immutabilization, the metaclass object will cache most informational
1785 methods that returns information about methods or attributes. Methods which
1786 would alter the class, such as C<add_attribute> and C<add_method>, will
1787 throw an error on an immutable metaclass object.
1789 The immutabilization system in L<Moose> takes much greater advantage
1790 of the inlining features than Class::MOP itself does.
1794 =item B<< $metaclass->make_immutable(%options) >>
1796 This method will create an immutable transformer and use it to make
1797 the class and its metaclass object immutable.
1799 This method accepts the following options:
1803 =item * inline_accessors
1805 =item * inline_constructor
1807 =item * inline_destructor
1809 These are all booleans indicating whether the specified method(s)
1812 By default, accessors and the constructor are inlined, but not the
1815 =item * immutable_trait
1817 The name of a class which will be used as a parent class for the
1818 metaclass object being made immutable. This "trait" implements the
1819 post-immutability functionality of the metaclass (but not the
1820 transformation itself).
1822 This defaults to L<Class::MOP::Class::Immutable::Trait>.
1824 =item * constructor_name
1826 This is the constructor method name. This defaults to "new".
1828 =item * constructor_class
1830 The name of the method metaclass for constructors. It will be used to
1831 generate the inlined constructor. This defaults to
1832 "Class::MOP::Method::Constructor".
1834 =item * replace_constructor
1836 This is a boolean indicating whether an existing constructor should be
1837 replaced when inlining a constructor. This defaults to false.
1839 =item * destructor_class
1841 The name of the method metaclass for destructors. It will be used to
1842 generate the inlined destructor. This defaults to
1843 "Class::MOP::Method::Denstructor".
1845 =item * replace_destructor
1847 This is a boolean indicating whether an existing destructor should be
1848 replaced when inlining a destructor. This defaults to false.
1852 =item B<< $metaclass->immutable_options >>
1854 Returns a hash of the options used when making the class immutable, including
1855 both defaults and anything supplied by the user in the call to C<<
1856 $metaclass->make_immutable >>. This is useful if you need to temporarily make
1857 a class mutable and then restore immutability as it was before.
1859 =item B<< $metaclass->make_mutable >>
1861 Calling this method reverse the immutabilization transformation.
1865 =head2 Method Modifiers
1867 Method modifiers are hooks which allow a method to be wrapped with
1868 I<before>, I<after> and I<around> method modifiers. Every time a
1869 method is called, its modifiers are also called.
1871 A class can modify its own methods, as well as methods defined in
1874 =head3 How method modifiers work?
1876 Method modifiers work by wrapping the original method and then
1877 replacing it in the class's symbol table. The wrappers will handle
1878 calling all the modifiers in the appropriate order and preserving the
1879 calling context for the original method.
1881 The return values of C<before> and C<after> modifiers are
1882 ignored. This is because their purpose is B<not> to filter the input
1883 and output of the primary method (this is done with an I<around>
1886 This may seem like an odd restriction to some, but doing this allows
1887 for simple code to be added at the beginning or end of a method call
1888 without altering the function of the wrapped method or placing any
1889 extra responsibility on the code of the modifier.
1891 Of course if you have more complex needs, you can use the C<around>
1892 modifier which allows you to change both the parameters passed to the
1893 wrapped method, as well as its return value.
1895 Before and around modifiers are called in last-defined-first-called
1896 order, while after modifiers are called in first-defined-first-called
1897 order. So the call tree might looks something like this:
1909 =head3 What is the performance impact?
1911 Of course there is a performance cost associated with method
1912 modifiers, but we have made every effort to make that cost directly
1913 proportional to the number of modifier features you use.
1915 The wrapping method does its best to B<only> do as much work as it
1916 absolutely needs to. In order to do this we have moved some of the
1917 performance costs to set-up time, where they are easier to amortize.
1919 All this said, our benchmarks have indicated the following:
1921 simple wrapper with no modifiers 100% slower
1922 simple wrapper with simple before modifier 400% slower
1923 simple wrapper with simple after modifier 450% slower
1924 simple wrapper with simple around modifier 500-550% slower
1925 simple wrapper with all 3 modifiers 1100% slower
1927 These numbers may seem daunting, but you must remember, every feature
1928 comes with some cost. To put things in perspective, just doing a
1929 simple C<AUTOLOAD> which does nothing but extract the name of the
1930 method called and return it costs about 400% over a normal method
1935 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
1937 This wraps the specified method with the supplied subroutine
1938 reference. The modifier will be called as a method itself, and will
1939 receive the same arguments as are passed to the method.
1941 When the modifier exits, the wrapped method will be called.
1943 The return value of the modifier will be ignored.
1945 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
1947 This wraps the specified method with the supplied subroutine
1948 reference. The modifier will be called as a method itself, and will
1949 receive the same arguments as are passed to the method.
1951 When the wrapped methods exits, the modifier will be called.
1953 The return value of the modifier will be ignored.
1955 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
1957 This wraps the specified method with the supplied subroutine
1960 The first argument passed to the modifier will be a subroutine
1961 reference to the wrapped method. The second argument is the object,
1962 and after that come any arguments passed when the method is called.
1964 The around modifier can choose to call the original method, as well as
1965 what arguments to pass if it does so.
1967 The return value of the modifier is what will be seen by the caller.
1971 =head2 Introspection
1975 =item B<< Class::MOP::Class->meta >>
1977 This will return a L<Class::MOP::Class> instance for this class.
1979 It should also be noted that L<Class::MOP> will actually bootstrap
1980 this module by installing a number of attribute meta-objects into its
1987 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1989 =head1 COPYRIGHT AND LICENSE
1991 Copyright 2006-2010 by Infinity Interactive, Inc.
1993 L<http://www.iinteractive.com>
1995 This library is free software; you can redistribute it and/or modify
1996 it under the same terms as Perl itself.