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;
11 use Class::MOP::MiniTrait;
14 use Scalar::Util 'blessed', 'reftype', 'weaken';
15 use Sub::Name 'subname';
16 use Devel::GlobalDestruction 'in_global_destruction';
18 use List::MoreUtils 'all';
20 our $VERSION = '1.09';
21 $VERSION = eval $VERSION;
22 our $AUTHORITY = 'cpan:STEVAN';
24 use base 'Class::MOP::Module',
25 'Class::MOP::Mixin::HasAttributes',
26 'Class::MOP::Mixin::HasMethods';
36 $package_name = shift;
39 $package_name = $options{package};
42 ($package_name && !ref($package_name))
43 || confess "You must pass a package name and it cannot be blessed";
45 return Class::MOP::get_metaclass_by_name($package_name)
46 || $class->_construct_class_instance(package => $package_name, @_);
50 my ( $class, @args ) = @_;
51 unshift @args, "package" if @args % 2;
53 my $old_metaclass = blessed($options{package})
55 : Class::MOP::get_metaclass_by_name($options{package});
56 $old_metaclass->_remove_generated_metaobjects
57 if $old_metaclass && $old_metaclass->isa('Class::MOP::Class');
58 my $new_metaclass = $class->SUPER::reinitialize(@args);
59 $new_metaclass->_restore_metaobjects_from($old_metaclass)
60 if $old_metaclass && $old_metaclass->isa('Class::MOP::Class');
61 return $new_metaclass;
64 # NOTE: (meta-circularity)
65 # this is a special form of _construct_instance
66 # (see below), which is used to construct class
67 # meta-object instances for any Class::MOP::*
68 # class. All other classes will use the more
69 # normal &construct_instance.
70 sub _construct_class_instance {
72 my $options = @_ == 1 ? $_[0] : {@_};
73 my $package_name = $options->{package};
74 (defined $package_name && $package_name)
75 || confess "You must pass a package name";
77 # return the metaclass if we have it cached,
78 # and it is still defined (it has not been
79 # reaped by DESTROY yet, which can happen
80 # annoyingly enough during global destruction)
82 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
88 ? $class->_real_ref_name
91 # now create the metaclass
93 if ($class eq 'Class::MOP::Class') {
94 $meta = $class->_new($options);
98 # it is safe to use meta here because
99 # class will always be a subclass of
100 # Class::MOP::Class, which defines meta
101 $meta = $class->meta->_construct_instance($options)
104 # and check the metaclass compatibility
105 $meta->_check_metaclass_compatibility();
107 Class::MOP::store_metaclass_by_name($package_name, $meta);
110 # we need to weaken any anon classes
111 # so that they can call DESTROY properly
112 Class::MOP::weaken_metaclass($package_name) if $meta->is_anon_class;
120 # NOTE: we need to deal with the possibility of class immutability here,
121 # and then get the name of the class appropriately
122 return $self->is_immutable
123 ? $self->_get_mutable_metaclass_name()
130 return Class::MOP::Class->initialize($class)->new_object(@_)
131 if $class ne __PACKAGE__;
133 my $options = @_ == 1 ? $_[0] : {@_};
136 # inherited from Class::MOP::Package
137 'package' => $options->{package},
140 # since the following attributes will
141 # actually be loaded from the symbol
142 # table, and actually bypass the instance
143 # entirely, we can just leave these things
144 # listed here for reference, because they
145 # should not actually have a value associated
147 'namespace' => \undef,
150 # inherited from Class::MOP::Module
152 'authority' => \undef,
154 # defined in Class::MOP::Class
155 'superclasses' => \undef,
158 'attribute_metaclass' =>
159 ( $options->{'attribute_metaclass'} || 'Class::MOP::Attribute' ),
160 'method_metaclass' =>
161 ( $options->{'method_metaclass'} || 'Class::MOP::Method' ),
162 'wrapped_method_metaclass' => (
163 $options->{'wrapped_method_metaclass'}
164 || 'Class::MOP::Method::Wrapped'
166 'instance_metaclass' =>
167 ( $options->{'instance_metaclass'} || 'Class::MOP::Instance' ),
168 'immutable_trait' => (
169 $options->{'immutable_trait'}
170 || 'Class::MOP::Class::Immutable::Trait'
172 'constructor_name' => ( $options->{constructor_name} || 'new' ),
173 'constructor_class' => (
174 $options->{constructor_class} || 'Class::MOP::Method::Constructor'
176 'destructor_class' => $options->{destructor_class},
180 sub reset_package_cache_flag { (shift)->{'_package_cache_flag'} = undef }
181 sub update_package_cache_flag {
184 # we can manually update the cache number
185 # since we are actually adding the method
186 # to our cache as well. This avoids us
187 # having to regenerate the method_map.
189 $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
192 ## Metaclass compatibility
194 my %base_metaclass = (
195 attribute_metaclass => 'Class::MOP::Attribute',
196 method_metaclass => 'Class::MOP::Method',
197 wrapped_method_metaclass => 'Class::MOP::Method::Wrapped',
198 instance_metaclass => 'Class::MOP::Instance',
199 constructor_class => 'Class::MOP::Method::Constructor',
200 destructor_class => 'Class::MOP::Method::Destructor',
203 sub _base_metaclasses { %base_metaclass }
206 sub _check_metaclass_compatibility {
209 my @superclasses = $self->superclasses
212 $self->_fix_metaclass_incompatibility(@superclasses);
214 my %base_metaclass = $self->_base_metaclasses;
216 # this is always okay ...
218 if ref($self) eq 'Class::MOP::Class'
220 my $meta = $self->$_;
221 !defined($meta) || $meta eq $base_metaclass{$_};
223 keys %base_metaclass;
225 for my $superclass (@superclasses) {
226 $self->_check_class_metaclass_compatibility($superclass);
229 for my $metaclass_type ( keys %base_metaclass ) {
230 next unless defined $self->$metaclass_type;
231 for my $superclass (@superclasses) {
232 $self->_check_single_metaclass_compatibility( $metaclass_type,
238 sub _check_class_metaclass_compatibility {
240 my ( $superclass_name ) = @_;
242 if (!$self->_class_metaclass_is_compatible($superclass_name)) {
243 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
245 my $super_meta_type = $super_meta->_real_ref_name;
247 confess "The metaclass of " . $self->name . " ("
248 . (ref($self)) . ")" . " is not compatible with "
249 . "the metaclass of its superclass, "
250 . $superclass_name . " (" . ($super_meta_type) . ")";
254 sub _class_metaclass_is_compatible {
256 my ( $superclass_name ) = @_;
258 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
261 my $super_meta_name = $super_meta->_real_ref_name;
263 return $self->_is_compatible_with($super_meta_name);
266 sub _check_single_metaclass_compatibility {
268 my ( $metaclass_type, $superclass_name ) = @_;
270 if (!$self->_single_metaclass_is_compatible($metaclass_type, $superclass_name)) {
271 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
272 my $metaclass_type_name = $metaclass_type;
273 $metaclass_type_name =~ s/_(?:meta)?class$//;
274 $metaclass_type_name =~ s/_/ /g;
275 confess "The $metaclass_type_name metaclass for "
276 . $self->name . " (" . ($self->$metaclass_type)
277 . ")" . " is not compatible with the "
278 . "$metaclass_type_name metaclass of its "
279 . "superclass, $superclass_name ("
280 . ($super_meta->$metaclass_type) . ")";
284 sub _single_metaclass_is_compatible {
286 my ( $metaclass_type, $superclass_name ) = @_;
288 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
291 # for instance, Moose::Meta::Class has a error_class attribute, but
292 # Class::MOP::Class doesn't - this shouldn't be an error
293 return 1 unless $super_meta->can($metaclass_type);
294 # for instance, Moose::Meta::Class has a destructor_class, but
295 # Class::MOP::Class doesn't - this shouldn't be an error
296 return 1 unless defined $super_meta->$metaclass_type;
297 # if metaclass is defined in superclass but not here, it's not compatible
298 # this is a really odd case
299 return 0 unless defined $self->$metaclass_type;
301 return $self->$metaclass_type->_is_compatible_with($super_meta->$metaclass_type);
304 sub _fix_metaclass_incompatibility {
306 my @supers = map { Class::MOP::Class->initialize($_) } @_;
309 for my $super (@supers) {
311 if $self->_can_fix_metaclass_incompatibility($super);
313 return unless $necessary;
315 for my $super (@supers) {
316 if (!$self->_class_metaclass_is_compatible($super->name)) {
317 $self->_fix_class_metaclass_incompatibility($super);
321 my %base_metaclass = $self->_base_metaclasses;
322 for my $metaclass_type (keys %base_metaclass) {
323 for my $super (@supers) {
324 if (!$self->_single_metaclass_is_compatible($metaclass_type, $super->name)) {
325 $self->_fix_single_metaclass_incompatibility(
326 $metaclass_type, $super
333 sub _can_fix_metaclass_incompatibility {
335 return $self->_can_fix_metaclass_incompatibility_by_subclassing(@_);
338 sub _can_fix_metaclass_incompatibility_by_subclassing {
340 my ($super_meta) = @_;
342 return 1 if $self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta);
344 my %base_metaclass = $self->_base_metaclasses;
345 for my $metaclass_type (keys %base_metaclass) {
346 return 1 if $self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta);
352 sub _can_fix_class_metaclass_incompatibility_by_subclassing {
354 my ($super_meta) = @_;
356 my $super_meta_name = $super_meta->_real_ref_name;
358 return $self->_can_be_made_compatible_with($super_meta_name);
361 sub _can_fix_single_metaclass_incompatibility_by_subclassing {
363 my ($metaclass_type, $super_meta) = @_;
365 my $specific_meta = $self->$metaclass_type;
366 return unless $super_meta->can($metaclass_type);
367 my $super_specific_meta = $super_meta->$metaclass_type;
369 # for instance, Moose::Meta::Class has a destructor_class, but
370 # Class::MOP::Class doesn't - this shouldn't be an error
371 return unless defined $super_specific_meta;
373 # if metaclass is defined in superclass but not here, it's fixable
374 # this is a really odd case
375 return 1 unless defined $specific_meta;
377 return $specific_meta->_can_be_made_compatible_with($super_specific_meta);
380 sub _fix_class_metaclass_incompatibility {
382 my ( $super_meta ) = @_;
384 if ($self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta)) {
386 || confess "Can't fix metaclass incompatibility for "
388 . " because it is not pristine.";
390 my $super_meta_name = $super_meta->_real_ref_name;
392 $self->_make_compatible_with($super_meta_name);
396 sub _fix_single_metaclass_incompatibility {
398 my ( $metaclass_type, $super_meta ) = @_;
400 if ($self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta)) {
402 || confess "Can't fix metaclass incompatibility for "
404 . " because it is not pristine.";
406 my $new_metaclass = $self->$metaclass_type
407 ? $self->$metaclass_type->_get_compatible_metaclass($super_meta->$metaclass_type)
408 : $super_meta->$metaclass_type;
409 $self->{$metaclass_type} = $new_metaclass;
413 sub _restore_metaobjects_from {
417 for my $method ($old_meta->_get_local_methods) {
418 $self->_make_metaobject_compatible($method);
419 $self->add_method($method->name => $method);
422 for my $attr (sort { $a->insertion_order <=> $b->insertion_order }
423 map { $old_meta->get_attribute($_) }
424 $old_meta->get_attribute_list) {
425 $self->_make_metaobject_compatible($attr);
426 $self->add_attribute($attr);
430 sub _remove_generated_metaobjects {
433 for my $attr (map { $self->get_attribute($_) } $self->get_attribute_list) {
434 $attr->remove_accessors;
438 sub _make_metaobject_compatible {
441 my $current_single_meta_name = $self->_get_associated_single_metaclass($object);
442 $object->_make_compatible_with($current_single_meta_name);
445 sub _get_associated_single_metaclass {
447 my ($single_meta_name) = @_;
449 my $current_single_meta_name;
450 if ($single_meta_name->isa('Class::MOP::Method')) {
451 $current_single_meta_name = $self->method_metaclass;
453 elsif ($single_meta_name->isa('Class::MOP::Attribute')) {
454 $current_single_meta_name = $self->attribute_metaclass;
457 confess "Can't make $single_meta_name compatible, it isn't an "
458 . "attribute or method metaclass.";
461 return $current_single_meta_name;
468 # this should be sufficient, if you have a
469 # use case where it is not, write a test and
471 my $ANON_CLASS_SERIAL = 0;
474 # we need a sufficiently annoying prefix
475 # this should suffice for now, this is
476 # used in a couple of places below, so
477 # need to put it up here for now.
478 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
482 no warnings 'uninitialized';
483 $self->name =~ /^$ANON_CLASS_PREFIX/o;
486 sub create_anon_class {
487 my ($class, %options) = @_;
488 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
489 return $class->create($package_name, %options);
493 # this will only get called for
494 # anon-classes, all other calls
495 # are assumed to occur during
496 # global destruction and so don't
497 # really need to be handled explicitly
501 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
503 no warnings 'uninitialized';
504 my $name = $self->name;
505 return unless $name =~ /^$ANON_CLASS_PREFIX/o;
507 # Moose does a weird thing where it replaces the metaclass for
508 # class when fixing metaclass incompatibility. In that case,
509 # we don't want to clean out the namespace now. We can detect
510 # that because Moose will explicitly update the singleton
511 # cache in Class::MOP.
512 my $current_meta = Class::MOP::get_metaclass_by_name($name);
513 return if $current_meta ne $self;
515 my ($serial_id) = ($name =~ /^$ANON_CLASS_PREFIX(\d+)/o);
517 @{$name . '::ISA'} = ();
518 %{$name . '::'} = ();
519 delete ${$ANON_CLASS_PREFIX}{$serial_id . '::'};
521 Class::MOP::remove_metaclass_by_name($name);
526 # creating classes with MOP ...
529 my ( $class, @args ) = @_;
531 unshift @args, 'package' if @args % 2 == 1;
533 my (%options) = @args;
534 my $package_name = $options{package};
536 (ref $options{superclasses} eq 'ARRAY')
537 || confess "You must pass an ARRAY ref of superclasses"
538 if exists $options{superclasses};
540 (ref $options{attributes} eq 'ARRAY')
541 || confess "You must pass an ARRAY ref of attributes"
542 if exists $options{attributes};
544 (ref $options{methods} eq 'HASH')
545 || confess "You must pass a HASH ref of methods"
546 if exists $options{methods};
548 my (%initialize_options) = @args;
549 delete @initialize_options{qw(
558 my $meta = $class->initialize( $package_name => %initialize_options );
560 $meta->_instantiate_module( $options{version}, $options{authority} );
563 $meta->add_method('meta' => sub {
564 if (Class::MOP::DEBUG_NO_META()) {
566 if (my $meta = try { $self->SUPER::meta }) {
567 return $meta if $meta->isa('Class::MOP::Class');
569 confess "'meta' method called by MOP internals"
570 if caller =~ /Class::MOP|metaclass/;
572 $class->initialize(ref($_[0]) || $_[0]);
573 }) unless $options{no_meta};
575 $meta->superclasses(@{$options{superclasses}})
576 if exists $options{superclasses};
578 # process attributes first, so that they can
579 # install accessors, but locally defined methods
580 # can then overwrite them. It is maybe a little odd, but
581 # I think this should be the order of things.
582 if (exists $options{attributes}) {
583 foreach my $attr (@{$options{attributes}}) {
584 $meta->add_attribute($attr);
587 if (exists $options{methods}) {
588 foreach my $method_name (keys %{$options{methods}}) {
589 $meta->add_method($method_name, $options{methods}->{$method_name});
598 # all these attribute readers will be bootstrapped
599 # away in the Class::MOP bootstrap section
601 sub instance_metaclass { $_[0]->{'instance_metaclass'} }
602 sub immutable_trait { $_[0]->{'immutable_trait'} }
603 sub constructor_class { $_[0]->{'constructor_class'} }
604 sub constructor_name { $_[0]->{'constructor_name'} }
605 sub destructor_class { $_[0]->{'destructor_class'} }
607 # Instance Construction & Cloning
613 # we need to protect the integrity of the
614 # Class::MOP::Class singletons here, so we
615 # delegate this to &construct_class_instance
616 # which will deal with the singletons
617 return $class->_construct_class_instance(@_)
618 if $class->name->isa('Class::MOP::Class');
619 return $class->_construct_instance(@_);
622 sub _construct_instance {
624 my $params = @_ == 1 ? $_[0] : {@_};
625 my $meta_instance = $class->get_meta_instance();
627 # the code below is almost certainly incorrect
628 # but this is foreign inheritance, so we might
629 # have to kludge it in the end.
631 if (my $instance_class = blessed($params->{__INSTANCE__})) {
632 ($instance_class eq $class->name)
633 || confess "Objects passed as the __INSTANCE__ parameter must "
634 . "already be blessed into the correct class, but "
635 . "$params->{__INSTANCE__} is not a " . $class->name;
636 $instance = $params->{__INSTANCE__};
638 elsif (exists $params->{__INSTANCE__}) {
639 confess "The __INSTANCE__ parameter must be a blessed reference, not "
640 . $params->{__INSTANCE__};
643 $instance = $meta_instance->create_instance();
645 foreach my $attr ($class->get_all_attributes()) {
646 $attr->initialize_instance_slot($meta_instance, $instance, $params);
649 # this will only work for a HASH instance type
650 if ($class->is_anon_class) {
651 (reftype($instance) eq 'HASH')
652 || confess "Currently only HASH based instances are supported with instance of anon-classes";
654 # At some point we should make this official
655 # as a reserved slot name, but right now I am
656 # going to keep it here.
657 # my $RESERVED_MOP_SLOT = '__MOP__';
658 $instance->{'__MOP__'} = $class;
664 sub get_meta_instance {
666 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
669 sub _create_meta_instance {
672 my $instance = $self->instance_metaclass->new(
673 associated_metaclass => $self,
674 attributes => [ $self->get_all_attributes() ],
677 $self->add_meta_instance_dependencies()
678 if $instance->is_dependent_on_superclasses();
683 sub inline_create_instance {
686 return $self->get_meta_instance->inline_create_instance(@_);
689 sub inline_rebless_instance {
692 return $self->get_meta_instance->inline_rebless_instance_structure(@_);
697 my $instance = shift;
698 (blessed($instance) && $instance->isa($class->name))
699 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
702 # we need to protect the integrity of the
703 # Class::MOP::Class singletons here, they
704 # should not be cloned.
705 return $instance if $instance->isa('Class::MOP::Class');
706 $class->_clone_instance($instance, @_);
709 sub _clone_instance {
710 my ($class, $instance, %params) = @_;
712 || confess "You can only clone instances, ($instance) is not a blessed instance";
713 my $meta_instance = $class->get_meta_instance();
714 my $clone = $meta_instance->clone_instance($instance);
715 foreach my $attr ($class->get_all_attributes()) {
716 if ( defined( my $init_arg = $attr->init_arg ) ) {
717 if (exists $params{$init_arg}) {
718 $attr->set_value($clone, $params{$init_arg});
725 sub _force_rebless_instance {
726 my ($self, $instance, %params) = @_;
727 my $old_metaclass = Class::MOP::class_of($instance);
729 $old_metaclass->rebless_instance_away($instance, $self, %params)
732 my $meta_instance = $self->get_meta_instance;
735 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
736 $meta_instance->rebless_instance_structure($_[1], $self);
738 $self->_fixup_attributes_after_rebless($instance, $old_metaclass, %params);
741 sub rebless_instance {
742 my ($self, $instance, %params) = @_;
743 my $old_metaclass = Class::MOP::class_of($instance);
745 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
746 $self->name->isa($old_class)
747 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
749 $self->_force_rebless_instance($_[1], %params);
754 sub rebless_instance_back {
755 my ( $self, $instance ) = @_;
756 my $old_metaclass = Class::MOP::class_of($instance);
759 = $old_metaclass ? $old_metaclass->name : blessed($instance);
760 $old_class->isa( $self->name )
762 "You may rebless only into a superclass of ($old_class), of which ("
766 $self->_force_rebless_instance($_[1]);
771 sub rebless_instance_away {
772 # this intentionally does nothing, it is just a hook
775 sub _fixup_attributes_after_rebless {
777 my ($instance, $rebless_from, %params) = @_;
778 my $meta_instance = $self->get_meta_instance;
780 for my $attr ( $rebless_from->get_all_attributes ) {
781 next if $self->find_attribute_by_name( $attr->name );
782 $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
785 foreach my $attr ( $self->get_all_attributes ) {
786 if ( $attr->has_value($instance) ) {
787 if ( defined( my $init_arg = $attr->init_arg ) ) {
788 $params{$init_arg} = $attr->get_value($instance)
789 unless exists $params{$init_arg};
792 $attr->set_value($instance, $attr->get_value($instance));
797 foreach my $attr ($self->get_all_attributes) {
798 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
802 sub _attach_attribute {
803 my ($self, $attribute) = @_;
804 $attribute->attach_to_class($self);
807 sub _post_add_attribute {
808 my ( $self, $attribute ) = @_;
810 $self->invalidate_meta_instances;
812 # invalidate package flag here
815 $attribute->install_accessors;
818 $self->remove_attribute( $attribute->name );
823 sub remove_attribute {
826 my $removed_attribute = $self->SUPER::remove_attribute(@_)
829 $self->invalidate_meta_instances;
831 $removed_attribute->remove_accessors;
832 $removed_attribute->detach_from_class;
834 return$removed_attribute;
837 sub find_attribute_by_name {
838 my ( $self, $attr_name ) = @_;
840 foreach my $class ( $self->linearized_isa ) {
841 # fetch the meta-class ...
842 my $meta = Class::MOP::Class->initialize($class);
843 return $meta->get_attribute($attr_name)
844 if $meta->has_attribute($attr_name);
850 sub get_all_attributes {
852 my %attrs = map { %{ Class::MOP::Class->initialize($_)->_attribute_map } }
853 reverse $self->linearized_isa;
854 return values %attrs;
862 my $isa = $self->get_or_add_package_symbol(
863 { sigil => '@', type => 'ARRAY', name => 'ISA' } );
870 # on 5.8 and below, we need to call
871 # a method to get Perl to detect
872 # a cycle in the class hierarchy
873 my $class = $self->name;
877 # we need to check the metaclass
878 # compatibility here so that we can
879 # be sure that the superclass is
880 # not potentially creating an issues
881 # we don't know about
883 $self->_check_metaclass_compatibility();
884 $self->_superclasses_updated();
890 sub _superclasses_updated {
892 $self->update_meta_instance_dependencies();
897 my $super_class = $self->name;
899 return @{ $super_class->mro::get_isarev() };
902 sub direct_subclasses {
904 my $super_class = $self->name;
909 } Class::MOP::Class->initialize($_)->superclasses
914 return @{ mro::get_linear_isa( (shift)->name ) };
917 sub class_precedence_list {
919 my $name = $self->name;
921 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
923 # We need to check for circular inheritance here
924 # if we are are not on 5.10, cause 5.8 detects it
925 # late. This will do nothing if all is well, and
926 # blow up otherwise. Yes, it's an ugly hack, better
927 # suggestions are welcome.
929 ($name || return)->isa('This is a test for circular inheritance')
932 # if our mro is c3, we can
933 # just grab the linear_isa
934 if (mro::get_mro($name) eq 'c3') {
935 return @{ mro::get_linear_isa($name) }
939 # we can't grab the linear_isa for dfs
940 # since it has all the duplicates
945 Class::MOP::Class->initialize($_)->class_precedence_list()
946 } $self->superclasses()
954 my $fetch_and_prepare_method = sub {
955 my ($self, $method_name) = @_;
956 my $wrapped_metaclass = $self->wrapped_method_metaclass;
958 my $method = $self->get_method($method_name);
959 # if we dont have local ...
961 # try to find the next method
962 $method = $self->find_next_method_by_name($method_name);
963 # die if it does not exist
965 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
966 # and now make sure to wrap it
967 # even if it is already wrapped
968 # because we need a new sub ref
969 $method = $wrapped_metaclass->wrap($method,
970 package_name => $self->name,
971 name => $method_name,
975 # now make sure we wrap it properly
976 $method = $wrapped_metaclass->wrap($method,
977 package_name => $self->name,
978 name => $method_name,
979 ) unless $method->isa($wrapped_metaclass);
981 $self->add_method($method_name => $method);
985 sub add_before_method_modifier {
986 my ($self, $method_name, $method_modifier) = @_;
987 (defined $method_name && length $method_name)
988 || confess "You must pass in a method name";
989 my $method = $fetch_and_prepare_method->($self, $method_name);
990 $method->add_before_modifier(
991 subname(':before' => $method_modifier)
995 sub add_after_method_modifier {
996 my ($self, $method_name, $method_modifier) = @_;
997 (defined $method_name && length $method_name)
998 || confess "You must pass in a method name";
999 my $method = $fetch_and_prepare_method->($self, $method_name);
1000 $method->add_after_modifier(
1001 subname(':after' => $method_modifier)
1005 sub add_around_method_modifier {
1006 my ($self, $method_name, $method_modifier) = @_;
1007 (defined $method_name && length $method_name)
1008 || confess "You must pass in a method name";
1009 my $method = $fetch_and_prepare_method->($self, $method_name);
1010 $method->add_around_modifier(
1011 subname(':around' => $method_modifier)
1016 # the methods above used to be named like this:
1017 # ${pkg}::${method}:(before|after|around)
1018 # but this proved problematic when using one modifier
1019 # to wrap multiple methods (something which is likely
1020 # to happen pretty regularly IMO). So instead of naming
1021 # it like this, I have chosen to just name them purely
1022 # with their modifier names, like so:
1023 # :(before|after|around)
1024 # The fact is that in a stack trace, it will be fairly
1025 # evident from the context what method they are attached
1026 # to, and so don't need the fully qualified name.
1029 sub find_method_by_name {
1030 my ($self, $method_name) = @_;
1031 (defined $method_name && length $method_name)
1032 || confess "You must define a method name to find";
1033 foreach my $class ($self->linearized_isa) {
1034 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1035 return $method if defined $method;
1040 sub get_all_methods {
1044 for my $class ( reverse $self->linearized_isa ) {
1045 my $meta = Class::MOP::Class->initialize($class);
1047 $methods{ $_->name } = $_ for $meta->_get_local_methods;
1050 return values %methods;
1053 sub get_all_method_names {
1056 return grep { !$uniq{$_}++ } map { Class::MOP::Class->initialize($_)->get_method_list } $self->linearized_isa;
1059 sub find_all_methods_by_name {
1060 my ($self, $method_name) = @_;
1061 (defined $method_name && length $method_name)
1062 || confess "You must define a method name to find";
1064 foreach my $class ($self->linearized_isa) {
1065 # fetch the meta-class ...
1066 my $meta = Class::MOP::Class->initialize($class);
1068 name => $method_name,
1070 code => $meta->get_method($method_name)
1071 } if $meta->has_method($method_name);
1076 sub find_next_method_by_name {
1077 my ($self, $method_name) = @_;
1078 (defined $method_name && length $method_name)
1079 || confess "You must define a method name to find";
1080 my @cpl = $self->linearized_isa;
1081 shift @cpl; # discard ourselves
1082 foreach my $class (@cpl) {
1083 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1084 return $method if defined $method;
1089 sub update_meta_instance_dependencies {
1092 if ( $self->{meta_instance_dependencies} ) {
1093 return $self->add_meta_instance_dependencies;
1097 sub add_meta_instance_dependencies {
1100 $self->remove_meta_instance_dependencies;
1102 my @attrs = $self->get_all_attributes();
1105 my @classes = grep { not $seen{ $_->name }++ }
1106 map { $_->associated_class } @attrs;
1108 foreach my $class (@classes) {
1109 $class->add_dependent_meta_instance($self);
1112 $self->{meta_instance_dependencies} = \@classes;
1115 sub remove_meta_instance_dependencies {
1118 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
1119 foreach my $class (@$classes) {
1120 $class->remove_dependent_meta_instance($self);
1130 sub add_dependent_meta_instance {
1131 my ( $self, $metaclass ) = @_;
1132 push @{ $self->{dependent_meta_instances} }, $metaclass;
1135 sub remove_dependent_meta_instance {
1136 my ( $self, $metaclass ) = @_;
1137 my $name = $metaclass->name;
1138 @$_ = grep { $_->name ne $name } @$_
1139 for $self->{dependent_meta_instances};
1142 sub invalidate_meta_instances {
1144 $_->invalidate_meta_instance()
1145 for $self, @{ $self->{dependent_meta_instances} };
1148 sub invalidate_meta_instance {
1150 undef $self->{_meta_instance};
1153 # check if we can reinitialize
1157 # if any local attr is defined
1158 return if $self->get_attribute_list;
1160 # or any non-declared methods
1161 for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1162 return if $method->isa("Class::MOP::Method::Generated");
1163 # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1171 sub is_mutable { 1 }
1172 sub is_immutable { 0 }
1174 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1176 sub _immutable_options {
1177 my ( $self, @args ) = @_;
1180 inline_accessors => 1,
1181 inline_constructor => 1,
1182 inline_destructor => 0,
1184 immutable_trait => $self->immutable_trait,
1185 constructor_name => $self->constructor_name,
1186 constructor_class => $self->constructor_class,
1187 destructor_class => $self->destructor_class,
1192 sub make_immutable {
1193 my ( $self, @args ) = @_;
1195 if ( $self->is_mutable ) {
1196 $self->_initialize_immutable( $self->_immutable_options(@args) );
1197 $self->_rebless_as_immutable(@args);
1208 if ( $self->is_immutable ) {
1209 my @args = $self->immutable_options;
1210 $self->_rebless_as_mutable();
1211 $self->_remove_inlined_code(@args);
1212 delete $self->{__immutable};
1220 sub _rebless_as_immutable {
1221 my ( $self, @args ) = @_;
1223 $self->{__immutable}{original_class} = ref $self;
1225 bless $self => $self->_immutable_metaclass(@args);
1228 sub _immutable_metaclass {
1229 my ( $self, %args ) = @_;
1231 if ( my $class = $args{immutable_metaclass} ) {
1235 my $trait = $args{immutable_trait} = $self->immutable_trait
1236 || confess "no immutable trait specified for $self";
1238 my $meta = $self->meta;
1239 my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1243 if ( $meta_attr and $trait eq $meta_attr->default ) {
1244 # if the trait is the same as the default we try and pick a
1245 # predictable name for the immutable metaclass
1246 $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1249 $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1250 $trait, 'ForMetaClass', ref($self);
1254 if Class::MOP::is_class_loaded($class_name);
1256 # If the metaclass is a subclass of CMOP::Class which has had
1257 # metaclass roles applied (via Moose), then we want to make sure
1258 # that we preserve that anonymous class (see Fey::ORM for an
1259 # example of where this matters).
1260 my $meta_name = $meta->_real_ref_name;
1262 my $immutable_meta = $meta_name->create(
1264 superclasses => [ ref $self ],
1267 Class::MOP::MiniTrait::apply( $immutable_meta, $trait );
1269 $immutable_meta->make_immutable(
1270 inline_constructor => 0,
1271 inline_accessors => 0,
1277 sub _remove_inlined_code {
1280 $self->remove_method( $_->name ) for $self->_inlined_methods;
1282 delete $self->{__immutable}{inlined_methods};
1285 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1287 sub _add_inlined_method {
1288 my ( $self, $method ) = @_;
1290 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1293 sub _initialize_immutable {
1294 my ( $self, %args ) = @_;
1296 $self->{__immutable}{options} = \%args;
1297 $self->_install_inlined_code(%args);
1300 sub _install_inlined_code {
1301 my ( $self, %args ) = @_;
1304 $self->_inline_accessors(%args) if $args{inline_accessors};
1305 $self->_inline_constructor(%args) if $args{inline_constructor};
1306 $self->_inline_destructor(%args) if $args{inline_destructor};
1309 sub _rebless_as_mutable {
1312 bless $self, $self->_get_mutable_metaclass_name;
1317 sub _inline_accessors {
1320 foreach my $attr_name ( $self->get_attribute_list ) {
1321 $self->get_attribute($attr_name)->install_accessors(1);
1325 sub _inline_constructor {
1326 my ( $self, %args ) = @_;
1328 my $name = $args{constructor_name};
1329 # A class may not even have a constructor, and that's okay.
1330 return unless defined $name;
1332 if ( $self->has_method($name) && !$args{replace_constructor} ) {
1333 my $class = $self->name;
1334 warn "Not inlining a constructor for $class since it defines"
1335 . " its own constructor.\n"
1336 . "If you are certain you don't need to inline your"
1337 . " constructor, specify inline_constructor => 0 in your"
1338 . " call to $class->meta->make_immutable\n";
1342 my $constructor_class = $args{constructor_class};
1344 Class::MOP::load_class($constructor_class);
1346 my $constructor = $constructor_class->new(
1350 package_name => $self->name,
1354 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1355 $self->add_method( $name => $constructor );
1356 $self->_add_inlined_method($constructor);
1360 sub _inline_destructor {
1361 my ( $self, %args ) = @_;
1363 ( exists $args{destructor_class} && defined $args{destructor_class} )
1364 || confess "The 'inline_destructor' option is present, but "
1365 . "no destructor class was specified";
1367 if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1368 my $class = $self->name;
1369 warn "Not inlining a destructor for $class since it defines"
1370 . " its own destructor.\n";
1374 my $destructor_class = $args{destructor_class};
1376 Class::MOP::load_class($destructor_class);
1378 return unless $destructor_class->is_needed($self);
1380 my $destructor = $destructor_class->new(
1383 package_name => $self->name,
1387 if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1388 $self->add_method( 'DESTROY' => $destructor );
1389 $self->_add_inlined_method($destructor);
1401 Class::MOP::Class - Class Meta Object
1405 # assuming that class Foo
1406 # has been defined, you can
1408 # use this for introspection ...
1410 # add a method to Foo ...
1411 Foo->meta->add_method( 'bar' => sub {...} )
1413 # get a list of all the classes searched
1414 # the method dispatcher in the correct order
1415 Foo->meta->class_precedence_list()
1417 # remove a method from Foo
1418 Foo->meta->remove_method('bar');
1420 # or use this to actually create classes ...
1422 Class::MOP::Class->create(
1425 superclasses => ['Foo'],
1427 Class::MOP::Attribute->new('$bar'),
1428 Class::MOP::Attribute->new('$baz'),
1431 calculate_bar => sub {...},
1432 construct_baz => sub {...}
1439 The Class Protocol is the largest and most complex part of the
1440 Class::MOP meta-object protocol. It controls the introspection and
1441 manipulation of Perl 5 classes, and it can create them as well. The
1442 best way to understand what this module can do is to read the
1443 documentation for each of its methods.
1447 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1451 =head2 Class construction
1453 These methods all create new C<Class::MOP::Class> objects. These
1454 objects can represent existing classes or they can be used to create
1455 new classes from scratch.
1457 The metaclass object for a given class is a singleton. If you attempt
1458 to create a metaclass for the same class twice, you will just get the
1463 =item B<< Class::MOP::Class->create($package_name, %options) >>
1465 This method creates a new C<Class::MOP::Class> object with the given
1466 package name. It accepts a number of options:
1472 An optional version number for the newly created package.
1476 An optional authority for the newly created package.
1478 =item * superclasses
1480 An optional array reference of superclass names.
1484 An optional hash reference of methods for the class. The keys of the
1485 hash reference are method names and values are subroutine references.
1489 An optional array reference of L<Class::MOP::Attribute> objects.
1493 If true, a C<meta> method will not be installed into the class.
1497 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1499 This method works just like C<< Class::MOP::Class->create >> but it
1500 creates an "anonymous" class. In fact, the class does have a name, but
1501 that name is a unique name generated internally by this module.
1503 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1504 parameters that C<create> accepts.
1506 Anonymous classes are destroyed once the metaclass they are attached
1507 to goes out of scope, and will be removed from Perl's internal symbol
1510 All instances of an anonymous class keep a special reference to the
1511 metaclass object, which prevents the metaclass from going out of scope
1512 while any instances exist.
1514 This only works if the instance is based on a hash reference, however.
1516 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1518 This method will initialize a C<Class::MOP::Class> object for the
1519 named package. Unlike C<create>, this method I<will not> create a new
1522 The purpose of this method is to retrieve a C<Class::MOP::Class>
1523 object for introspecting an existing class.
1525 If an existing C<Class::MOP::Class> object exists for the named
1526 package, it will be returned, and any options provided will be
1529 If the object does not yet exist, it will be created.
1531 The valid options that can be passed to this method are
1532 C<attribute_metaclass>, C<method_metaclass>,
1533 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1534 optional, and default to the appropriate class in the C<Class::MOP>
1539 =head2 Object instance construction and cloning
1541 These methods are all related to creating and/or cloning object
1546 =item B<< $metaclass->clone_object($instance, %params) >>
1548 This method clones an existing object instance. Any parameters you
1549 provide are will override existing attribute values in the object.
1551 This is a convenience method for cloning an object instance, then
1552 blessing it into the appropriate package.
1554 You could implement a clone method in your class, using this method:
1557 my ($self, %params) = @_;
1558 $self->meta->clone_object($self, %params);
1561 =item B<< $metaclass->rebless_instance($instance, %params) >>
1563 This method changes the class of C<$instance> to the metaclass's class.
1565 You can only rebless an instance into a subclass of its current
1566 class. If you pass any additional parameters, these will be treated
1567 like constructor parameters and used to initialize the object's
1568 attributes. Any existing attributes that are already set will be
1571 Before reblessing the instance, this method will call
1572 C<rebless_instance_away> on the instance's current metaclass. This method
1573 will be passed the instance, the new metaclass, and any parameters
1574 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1575 does nothing; it is merely a hook.
1577 =item B<< $metaclass->rebless_instance_back($instance) >>
1579 Does the same thing as C<rebless_instance>, except that you can only
1580 rebless an instance into one of its superclasses. Any attributes that
1581 do not exist in the superclass will be deinitialized.
1583 This is a much more dangerous operation than C<rebless_instance>,
1584 especially when multiple inheritance is involved, so use this carefully!
1586 =item B<< $metaclass->new_object(%params) >>
1588 This method is used to create a new object of the metaclass's
1589 class. Any parameters you provide are used to initialize the
1590 instance's attributes. A special C<__INSTANCE__> key can be passed to
1591 provide an already generated instance, rather than having Class::MOP
1592 generate it for you. This is mostly useful for using Class::MOP with
1593 foreign classes which generate instances using their own constructors.
1595 =item B<< $metaclass->instance_metaclass >>
1597 Returns the class name of the instance metaclass. See
1598 L<Class::MOP::Instance> for more information on the instance
1601 =item B<< $metaclass->get_meta_instance >>
1603 Returns an instance of the C<instance_metaclass> to be used in the
1604 construction of a new instance of the class.
1606 =item B<< $metaclass->inline_create_instance($class_var) >>
1608 =item B<< $metaclass->inline_rebless_instance($instance_var, $class_var) >>
1610 These methods takes variable names, and use them to create an inline snippet
1611 of code that will create a new instance of the class.
1615 =head2 Informational predicates
1617 These are a few predicate methods for asking information about the
1622 =item B<< $metaclass->is_anon_class >>
1624 This returns true if the class was created by calling C<<
1625 Class::MOP::Class->create_anon_class >>.
1627 =item B<< $metaclass->is_mutable >>
1629 This returns true if the class is still mutable.
1631 =item B<< $metaclass->is_immutable >>
1633 This returns true if the class has been made immutable.
1635 =item B<< $metaclass->is_pristine >>
1637 A class is I<not> pristine if it has non-inherited attributes or if it
1638 has any generated methods.
1642 =head2 Inheritance Relationships
1646 =item B<< $metaclass->superclasses(@superclasses) >>
1648 This is a read-write accessor which represents the superclass
1649 relationships of the metaclass's class.
1651 This is basically sugar around getting and setting C<@ISA>.
1653 =item B<< $metaclass->class_precedence_list >>
1655 This returns a list of all of the class's ancestor classes. The
1656 classes are returned in method dispatch order.
1658 =item B<< $metaclass->linearized_isa >>
1660 This returns a list based on C<class_precedence_list> but with all
1663 =item B<< $metaclass->subclasses >>
1665 This returns a list of all subclasses for this class, even indirect
1668 =item B<< $metaclass->direct_subclasses >>
1670 This returns a list of immediate subclasses for this class, which does not
1671 include indirect subclasses.
1675 =head2 Method introspection and creation
1677 These methods allow you to introspect a class's methods, as well as
1678 add, remove, or change methods.
1680 Determining what is truly a method in a Perl 5 class requires some
1681 heuristics (aka guessing).
1683 Methods defined outside the package with a fully qualified name (C<sub
1684 Package::name { ... }>) will be included. Similarly, methods named
1685 with a fully qualified name using L<Sub::Name> are also included.
1687 However, we attempt to ignore imported functions.
1689 Ultimately, we are using heuristics to determine what truly is a
1690 method in a class, and these heuristics may get the wrong answer in
1691 some edge cases. However, for most "normal" cases the heuristics work
1696 =item B<< $metaclass->get_method($method_name) >>
1698 This will return a L<Class::MOP::Method> for the specified
1699 C<$method_name>. If the class does not have the specified method, it
1702 =item B<< $metaclass->has_method($method_name) >>
1704 Returns a boolean indicating whether or not the class defines the
1705 named method. It does not include methods inherited from parent
1708 =item B<< $metaclass->get_method_list >>
1710 This will return a list of method I<names> for all methods defined in
1713 =item B<< $metaclass->add_method($method_name, $method) >>
1715 This method takes a method name and a subroutine reference, and adds
1716 the method to the class.
1718 The subroutine reference can be a L<Class::MOP::Method>, and you are
1719 strongly encouraged to pass a meta method object instead of a code
1720 reference. If you do so, that object gets stored as part of the
1721 class's method map directly. If not, the meta information will have to
1722 be recreated later, and may be incorrect.
1724 If you provide a method object, this method will clone that object if
1725 the object's package name does not match the class name. This lets us
1726 track the original source of any methods added from other classes
1727 (notably Moose roles).
1729 =item B<< $metaclass->remove_method($method_name) >>
1731 Remove the named method from the class. This method returns the
1732 L<Class::MOP::Method> object for the method.
1734 =item B<< $metaclass->method_metaclass >>
1736 Returns the class name of the method metaclass, see
1737 L<Class::MOP::Method> for more information on the method metaclass.
1739 =item B<< $metaclass->wrapped_method_metaclass >>
1741 Returns the class name of the wrapped method metaclass, see
1742 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1745 =item B<< $metaclass->get_all_methods >>
1747 This will traverse the inheritance hierarchy and return a list of all
1748 the L<Class::MOP::Method> objects for this class and its parents.
1750 =item B<< $metaclass->find_method_by_name($method_name) >>
1752 This will return a L<Class::MOP::Method> for the specified
1753 C<$method_name>. If the class does not have the specified method, it
1756 Unlike C<get_method>, this method I<will> look for the named method in
1759 =item B<< $metaclass->get_all_method_names >>
1761 This will return a list of method I<names> for all of this class's
1762 methods, including inherited methods.
1764 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1766 This method looks for the named method in the class and all of its
1767 parents. It returns every matching method it finds in the inheritance
1768 tree, so it returns a list of methods.
1770 Each method is returned as a hash reference with three keys. The keys
1771 are C<name>, C<class>, and C<code>. The C<code> key has a
1772 L<Class::MOP::Method> object as its value.
1774 The list of methods is distinct.
1776 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1778 This method returns the first method in any superclass matching the
1779 given name. It is effectively the method that C<SUPER::$method_name>
1784 =head2 Attribute introspection and creation
1786 Because Perl 5 does not have a core concept of attributes in classes,
1787 we can only return information about attributes which have been added
1788 via this class's methods. We cannot discover information about
1789 attributes which are defined in terms of "regular" Perl 5 methods.
1793 =item B<< $metaclass->get_attribute($attribute_name) >>
1795 This will return a L<Class::MOP::Attribute> for the specified
1796 C<$attribute_name>. If the class does not have the specified
1797 attribute, it returns C<undef>.
1799 NOTE that get_attribute does not search superclasses, for that you
1800 need to use C<find_attribute_by_name>.
1802 =item B<< $metaclass->has_attribute($attribute_name) >>
1804 Returns a boolean indicating whether or not the class defines the
1805 named attribute. It does not include attributes inherited from parent
1808 =item B<< $metaclass->get_attribute_list >>
1810 This will return a list of attributes I<names> for all attributes
1811 defined in this class. Note that this operates on the current class
1812 only, it does not traverse the inheritance hierarchy.
1814 =item B<< $metaclass->get_all_attributes >>
1816 This will traverse the inheritance hierarchy and return a list of all
1817 the L<Class::MOP::Attribute> objects for this class and its parents.
1819 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1821 This will return a L<Class::MOP::Attribute> for the specified
1822 C<$attribute_name>. If the class does not have the specified
1823 attribute, it returns C<undef>.
1825 Unlike C<get_attribute>, this attribute I<will> look for the named
1826 attribute in superclasses.
1828 =item B<< $metaclass->add_attribute(...) >>
1830 This method accepts either an existing L<Class::MOP::Attribute>
1831 object or parameters suitable for passing to that class's C<new>
1834 The attribute provided will be added to the class.
1836 Any accessor methods defined by the attribute will be added to the
1837 class when the attribute is added.
1839 If an attribute of the same name already exists, the old attribute
1840 will be removed first.
1842 =item B<< $metaclass->remove_attribute($attribute_name) >>
1844 This will remove the named attribute from the class, and
1845 L<Class::MOP::Attribute> object.
1847 Removing an attribute also removes any accessor methods defined by the
1850 However, note that removing an attribute will only affect I<future>
1851 object instances created for this class, not existing instances.
1853 =item B<< $metaclass->attribute_metaclass >>
1855 Returns the class name of the attribute metaclass for this class. By
1856 default, this is L<Class::MOP::Attribute>.
1860 =head2 Class Immutability
1862 Making a class immutable "freezes" the class definition. You can no
1863 longer call methods which alter the class, such as adding or removing
1864 methods or attributes.
1866 Making a class immutable lets us optimize the class by inlining some
1867 methods, and also allows us to optimize some methods on the metaclass
1870 After immutabilization, the metaclass object will cache most informational
1871 methods that returns information about methods or attributes. Methods which
1872 would alter the class, such as C<add_attribute> and C<add_method>, will
1873 throw an error on an immutable metaclass object.
1875 The immutabilization system in L<Moose> takes much greater advantage
1876 of the inlining features than Class::MOP itself does.
1880 =item B<< $metaclass->make_immutable(%options) >>
1882 This method will create an immutable transformer and use it to make
1883 the class and its metaclass object immutable.
1885 This method accepts the following options:
1889 =item * inline_accessors
1891 =item * inline_constructor
1893 =item * inline_destructor
1895 These are all booleans indicating whether the specified method(s)
1898 By default, accessors and the constructor are inlined, but not the
1901 =item * immutable_trait
1903 The name of a class which will be used as a parent class for the
1904 metaclass object being made immutable. This "trait" implements the
1905 post-immutability functionality of the metaclass (but not the
1906 transformation itself).
1908 This defaults to L<Class::MOP::Class::Immutable::Trait>.
1910 =item * constructor_name
1912 This is the constructor method name. This defaults to "new".
1914 =item * constructor_class
1916 The name of the method metaclass for constructors. It will be used to
1917 generate the inlined constructor. This defaults to
1918 "Class::MOP::Method::Constructor".
1920 =item * replace_constructor
1922 This is a boolean indicating whether an existing constructor should be
1923 replaced when inlining a constructor. This defaults to false.
1925 =item * destructor_class
1927 The name of the method metaclass for destructors. It will be used to
1928 generate the inlined destructor. This defaults to
1929 "Class::MOP::Method::Denstructor".
1931 =item * replace_destructor
1933 This is a boolean indicating whether an existing destructor should be
1934 replaced when inlining a destructor. This defaults to false.
1938 =item B<< $metaclass->immutable_options >>
1940 Returns a hash of the options used when making the class immutable, including
1941 both defaults and anything supplied by the user in the call to C<<
1942 $metaclass->make_immutable >>. This is useful if you need to temporarily make
1943 a class mutable and then restore immutability as it was before.
1945 =item B<< $metaclass->make_mutable >>
1947 Calling this method reverse the immutabilization transformation.
1951 =head2 Method Modifiers
1953 Method modifiers are hooks which allow a method to be wrapped with
1954 I<before>, I<after> and I<around> method modifiers. Every time a
1955 method is called, its modifiers are also called.
1957 A class can modify its own methods, as well as methods defined in
1960 =head3 How method modifiers work?
1962 Method modifiers work by wrapping the original method and then
1963 replacing it in the class's symbol table. The wrappers will handle
1964 calling all the modifiers in the appropriate order and preserving the
1965 calling context for the original method.
1967 The return values of C<before> and C<after> modifiers are
1968 ignored. This is because their purpose is B<not> to filter the input
1969 and output of the primary method (this is done with an I<around>
1972 This may seem like an odd restriction to some, but doing this allows
1973 for simple code to be added at the beginning or end of a method call
1974 without altering the function of the wrapped method or placing any
1975 extra responsibility on the code of the modifier.
1977 Of course if you have more complex needs, you can use the C<around>
1978 modifier which allows you to change both the parameters passed to the
1979 wrapped method, as well as its return value.
1981 Before and around modifiers are called in last-defined-first-called
1982 order, while after modifiers are called in first-defined-first-called
1983 order. So the call tree might looks something like this:
1995 =head3 What is the performance impact?
1997 Of course there is a performance cost associated with method
1998 modifiers, but we have made every effort to make that cost directly
1999 proportional to the number of modifier features you use.
2001 The wrapping method does its best to B<only> do as much work as it
2002 absolutely needs to. In order to do this we have moved some of the
2003 performance costs to set-up time, where they are easier to amortize.
2005 All this said, our benchmarks have indicated the following:
2007 simple wrapper with no modifiers 100% slower
2008 simple wrapper with simple before modifier 400% slower
2009 simple wrapper with simple after modifier 450% slower
2010 simple wrapper with simple around modifier 500-550% slower
2011 simple wrapper with all 3 modifiers 1100% slower
2013 These numbers may seem daunting, but you must remember, every feature
2014 comes with some cost. To put things in perspective, just doing a
2015 simple C<AUTOLOAD> which does nothing but extract the name of the
2016 method called and return it costs about 400% over a normal method
2021 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
2023 This wraps the specified method with the supplied subroutine
2024 reference. The modifier will be called as a method itself, and will
2025 receive the same arguments as are passed to the method.
2027 When the modifier exits, the wrapped method will be called.
2029 The return value of the modifier will be ignored.
2031 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
2033 This wraps the specified method with the supplied subroutine
2034 reference. The modifier will be called as a method itself, and will
2035 receive the same arguments as are passed to the method.
2037 When the wrapped methods exits, the modifier will be called.
2039 The return value of the modifier will be ignored.
2041 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
2043 This wraps the specified method with the supplied subroutine
2046 The first argument passed to the modifier will be a subroutine
2047 reference to the wrapped method. The second argument is the object,
2048 and after that come any arguments passed when the method is called.
2050 The around modifier can choose to call the original method, as well as
2051 what arguments to pass if it does so.
2053 The return value of the modifier is what will be seen by the caller.
2057 =head2 Introspection
2061 =item B<< Class::MOP::Class->meta >>
2063 This will return a L<Class::MOP::Class> instance for this class.
2065 It should also be noted that L<Class::MOP> will actually bootstrap
2066 this module by installing a number of attribute meta-objects into its
2073 Stevan Little E<lt>stevan@iinteractive.comE<gt>
2075 =head1 COPYRIGHT AND LICENSE
2077 Copyright 2006-2010 by Infinity Interactive, Inc.
2079 L<http://www.iinteractive.com>
2081 This library is free software; you can redistribute it and/or modify
2082 it under the same terms as Perl itself.