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.08';
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 my $new_metaclass = $class->SUPER::reinitialize(@args);
57 $new_metaclass->_restore_metaobjects_from($old_metaclass)
59 return $new_metaclass;
62 # NOTE: (meta-circularity)
63 # this is a special form of _construct_instance
64 # (see below), which is used to construct class
65 # meta-object instances for any Class::MOP::*
66 # class. All other classes will use the more
67 # normal &construct_instance.
68 sub _construct_class_instance {
70 my $options = @_ == 1 ? $_[0] : {@_};
71 my $package_name = $options->{package};
72 (defined $package_name && $package_name)
73 || confess "You must pass a package name";
75 # return the metaclass if we have it cached,
76 # and it is still defined (it has not been
77 # reaped by DESTROY yet, which can happen
78 # annoyingly enough during global destruction)
80 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
86 ? $class->_real_ref_name
89 # now create the metaclass
91 if ($class eq 'Class::MOP::Class') {
92 $meta = $class->_new($options);
96 # it is safe to use meta here because
97 # class will always be a subclass of
98 # Class::MOP::Class, which defines meta
99 $meta = $class->meta->_construct_instance($options)
102 # and check the metaclass compatibility
103 $meta->_check_metaclass_compatibility();
105 Class::MOP::store_metaclass_by_name($package_name, $meta);
108 # we need to weaken any anon classes
109 # so that they can call DESTROY properly
110 Class::MOP::weaken_metaclass($package_name) if $meta->is_anon_class;
118 # NOTE: we need to deal with the possibility of class immutability here,
119 # and then get the name of the class appropriately
120 return $self->is_immutable
121 ? $self->_get_mutable_metaclass_name()
128 return Class::MOP::Class->initialize($class)->new_object(@_)
129 if $class ne __PACKAGE__;
131 my $options = @_ == 1 ? $_[0] : {@_};
134 # inherited from Class::MOP::Package
135 'package' => $options->{package},
138 # since the following attributes will
139 # actually be loaded from the symbol
140 # table, and actually bypass the instance
141 # entirely, we can just leave these things
142 # listed here for reference, because they
143 # should not actually have a value associated
145 'namespace' => \undef,
148 # inherited from Class::MOP::Module
150 'authority' => \undef,
152 # defined in Class::MOP::Class
153 'superclasses' => \undef,
156 'attribute_metaclass' =>
157 ( $options->{'attribute_metaclass'} || 'Class::MOP::Attribute' ),
158 'method_metaclass' =>
159 ( $options->{'method_metaclass'} || 'Class::MOP::Method' ),
160 'wrapped_method_metaclass' => (
161 $options->{'wrapped_method_metaclass'}
162 || 'Class::MOP::Method::Wrapped'
164 'instance_metaclass' =>
165 ( $options->{'instance_metaclass'} || 'Class::MOP::Instance' ),
166 'immutable_trait' => (
167 $options->{'immutable_trait'}
168 || 'Class::MOP::Class::Immutable::Trait'
170 'constructor_name' => ( $options->{constructor_name} || 'new' ),
171 'constructor_class' => (
172 $options->{constructor_class} || 'Class::MOP::Method::Constructor'
174 'destructor_class' => $options->{destructor_class},
178 sub reset_package_cache_flag { (shift)->{'_package_cache_flag'} = undef }
179 sub update_package_cache_flag {
182 # we can manually update the cache number
183 # since we are actually adding the method
184 # to our cache as well. This avoids us
185 # having to regenerate the method_map.
187 $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
190 ## Metaclass compatibility
192 my %base_metaclass = (
193 attribute_metaclass => 'Class::MOP::Attribute',
194 method_metaclass => 'Class::MOP::Method',
195 wrapped_method_metaclass => 'Class::MOP::Method::Wrapped',
196 instance_metaclass => 'Class::MOP::Instance',
197 constructor_class => 'Class::MOP::Method::Constructor',
198 destructor_class => 'Class::MOP::Method::Destructor',
201 sub _base_metaclasses { %base_metaclass }
204 sub _check_metaclass_compatibility {
207 my @superclasses = $self->superclasses
210 $self->_fix_metaclass_incompatibility(@superclasses);
212 my %base_metaclass = $self->_base_metaclasses;
214 # this is always okay ...
216 if ref($self) eq 'Class::MOP::Class'
218 my $meta = $self->$_;
219 !defined($meta) || $meta eq $base_metaclass{$_};
221 keys %base_metaclass;
223 for my $superclass (@superclasses) {
224 $self->_check_class_metaclass_compatibility($superclass);
227 for my $metaclass_type ( keys %base_metaclass ) {
228 next unless defined $self->$metaclass_type;
229 for my $superclass (@superclasses) {
230 $self->_check_single_metaclass_compatibility( $metaclass_type,
236 sub _class_metaclass_is_compatible {
238 my ( $superclass_name ) = @_;
240 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
243 my $super_meta_type = $super_meta->_real_ref_name;
245 return $self->isa($super_meta_type);
248 sub _check_class_metaclass_compatibility {
250 my ( $superclass_name ) = @_;
252 if (!$self->_class_metaclass_is_compatible($superclass_name)) {
253 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
255 my $super_meta_type = $super_meta->_real_ref_name;
257 confess "The metaclass of " . $self->name . " ("
258 . (ref($self)) . ")" . " is not compatible with "
259 . "the metaclass of its superclass, "
260 . $superclass_name . " (" . ($super_meta_type) . ")";
264 sub _single_metaclass_is_compatible {
266 my ( $metaclass_type, $superclass_name ) = @_;
268 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
271 # for instance, Moose::Meta::Class has a error_class attribute, but
272 # Class::MOP::Class doesn't - this shouldn't be an error
273 return 1 unless $super_meta->can($metaclass_type);
274 # for instance, Moose::Meta::Class has a destructor_class, but
275 # Class::MOP::Class doesn't - this shouldn't be an error
276 return 1 unless defined $super_meta->$metaclass_type;
277 # if metaclass is defined in superclass but not here, it's not compatible
278 # this is a really odd case
279 return 0 unless defined $self->$metaclass_type;
281 return $self->$metaclass_type->isa($super_meta->$metaclass_type);
284 sub _check_single_metaclass_compatibility {
286 my ( $metaclass_type, $superclass_name ) = @_;
288 if (!$self->_single_metaclass_is_compatible($metaclass_type, $superclass_name)) {
289 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
290 my $metaclass_type_name = $metaclass_type;
291 $metaclass_type_name =~ s/_(?:meta)?class$//;
292 $metaclass_type_name =~ s/_/ /g;
293 confess "The $metaclass_type_name metaclass for "
294 . $self->name . " (" . ($self->$metaclass_type)
295 . ")" . " is not compatible with the "
296 . "$metaclass_type_name metaclass of its "
297 . "superclass, $superclass_name ("
298 . ($super_meta->$metaclass_type) . ")";
302 sub _can_fix_class_metaclass_incompatibility_by_subclassing {
304 my ($super_meta) = @_;
306 my $super_meta_type = $super_meta->_real_ref_name;
308 return $super_meta_type ne blessed($self)
309 && $super_meta->isa(blessed($self));
312 sub _can_fix_single_metaclass_incompatibility_by_subclassing {
314 my ($metaclass_type, $super_meta) = @_;
316 my $specific_meta = $self->$metaclass_type;
317 return unless $super_meta->can($metaclass_type);
318 my $super_specific_meta = $super_meta->$metaclass_type;
320 # for instance, Moose::Meta::Class has a destructor_class, but
321 # Class::MOP::Class doesn't - this shouldn't be an error
322 return unless defined $super_specific_meta;
324 # if metaclass is defined in superclass but not here, it's fixable
325 # this is a really odd case
326 return 1 unless defined $specific_meta;
328 return $specific_meta ne $super_specific_meta
329 && $super_specific_meta->isa($specific_meta);
332 sub _can_fix_metaclass_incompatibility_by_subclassing {
334 my ($super_meta) = @_;
336 return 1 if $self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta);
338 my %base_metaclass = $self->_base_metaclasses;
339 for my $metaclass_type (keys %base_metaclass) {
340 return 1 if $self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta);
346 sub _can_fix_metaclass_incompatibility {
348 return $self->_can_fix_metaclass_incompatibility_by_subclassing(@_);
351 sub _fix_metaclass_incompatibility {
353 my @supers = map { Class::MOP::Class->initialize($_) } @_;
356 for my $super (@supers) {
358 if $self->_can_fix_metaclass_incompatibility($super);
360 return unless $necessary;
362 for my $super (@supers) {
363 if (!$self->_class_metaclass_is_compatible($super->name)) {
364 $self->_fix_class_metaclass_incompatibility($super);
368 my %base_metaclass = $self->_base_metaclasses;
369 for my $metaclass_type (keys %base_metaclass) {
370 for my $super (@supers) {
371 if (!$self->_single_metaclass_is_compatible($metaclass_type, $super->name)) {
372 $self->_fix_single_metaclass_incompatibility(
373 $metaclass_type, $super
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 $super_meta_name->meta->rebless_instance($self);
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 $self->{$metaclass_type} = $super_meta->$metaclass_type;
410 sub _get_associated_single_metaclass {
412 my ($single_meta_name) = @_;
414 my $current_single_meta_name;
415 if ($single_meta_name->isa('Class::MOP::Method')) {
416 $current_single_meta_name = $self->method_metaclass;
418 elsif ($single_meta_name->isa('Class::MOP::Attribute')) {
419 $current_single_meta_name = $self->attribute_metaclass;
422 confess "Can't make $single_meta_name compatible, it isn't an "
423 . "attribute or method metaclass.";
426 return $current_single_meta_name;
429 sub _get_compatible_single_metaclass_by_subclassing {
431 my ($single_meta_name) = @_;
433 my $current_single_meta_name = $self->_get_associated_single_metaclass($single_meta_name);
435 if ($single_meta_name->isa($current_single_meta_name)) {
436 return $single_meta_name;
438 elsif ($current_single_meta_name->isa($single_meta_name)) {
439 return $current_single_meta_name;
445 sub _get_compatible_single_metaclass {
447 my ($single_meta_name) = @_;
449 return $self->_get_compatible_single_metaclass_by_subclassing($single_meta_name);
452 sub _make_metaobject_compatible {
456 my $new_metaclass = $self->_get_compatible_single_metaclass(blessed($object));
458 if (!defined($new_metaclass)) {
459 confess "Can't make $object compatible with metaclass "
460 . $self->_get_associated_single_metaclass(blessed($object));
463 # XXX: is this sufficient? i think so... we should never lose attributes
465 bless($object, $new_metaclass)
466 if blessed($object) ne $new_metaclass;
471 sub _restore_metaobjects_from {
475 for my $method ($old_meta->_get_local_methods) {
476 $self->_make_metaobject_compatible($method);
477 $self->add_method($method->name => $method);
480 for my $attr (sort { $a->insertion_order <=> $b->insertion_order }
481 map { $old_meta->get_attribute($_) }
482 $old_meta->get_attribute_list) {
483 $self->_make_metaobject_compatible($attr);
484 $self->add_attribute($attr);
492 # this should be sufficient, if you have a
493 # use case where it is not, write a test and
495 my $ANON_CLASS_SERIAL = 0;
498 # we need a sufficiently annoying prefix
499 # this should suffice for now, this is
500 # used in a couple of places below, so
501 # need to put it up here for now.
502 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
506 no warnings 'uninitialized';
507 $self->name =~ /^$ANON_CLASS_PREFIX/o;
510 sub create_anon_class {
511 my ($class, %options) = @_;
512 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
513 return $class->create($package_name, %options);
517 # this will only get called for
518 # anon-classes, all other calls
519 # are assumed to occur during
520 # global destruction and so don't
521 # really need to be handled explicitly
525 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
527 no warnings 'uninitialized';
528 my $name = $self->name;
529 return unless $name =~ /^$ANON_CLASS_PREFIX/o;
531 # Moose does a weird thing where it replaces the metaclass for
532 # class when fixing metaclass incompatibility. In that case,
533 # we don't want to clean out the namespace now. We can detect
534 # that because Moose will explicitly update the singleton
535 # cache in Class::MOP.
536 my $current_meta = Class::MOP::get_metaclass_by_name($name);
537 return if $current_meta ne $self;
539 my ($serial_id) = ($name =~ /^$ANON_CLASS_PREFIX(\d+)/o);
541 @{$name . '::ISA'} = ();
542 %{$name . '::'} = ();
543 delete ${$ANON_CLASS_PREFIX}{$serial_id . '::'};
545 Class::MOP::remove_metaclass_by_name($name);
550 # creating classes with MOP ...
553 my ( $class, @args ) = @_;
555 unshift @args, 'package' if @args % 2 == 1;
557 my (%options) = @args;
558 my $package_name = $options{package};
560 (ref $options{superclasses} eq 'ARRAY')
561 || confess "You must pass an ARRAY ref of superclasses"
562 if exists $options{superclasses};
564 (ref $options{attributes} eq 'ARRAY')
565 || confess "You must pass an ARRAY ref of attributes"
566 if exists $options{attributes};
568 (ref $options{methods} eq 'HASH')
569 || confess "You must pass a HASH ref of methods"
570 if exists $options{methods};
572 my (%initialize_options) = @args;
573 delete @initialize_options{qw(
582 my $meta = $class->initialize( $package_name => %initialize_options );
584 $meta->_instantiate_module( $options{version}, $options{authority} );
587 $meta->add_method('meta' => sub {
588 if (Class::MOP::DEBUG_NO_META()) {
590 if (my $meta = try { $self->SUPER::meta }) {
591 return $meta if $meta->isa('Class::MOP::Class');
593 confess "'meta' method called by MOP internals"
594 if caller =~ /Class::MOP|metaclass/;
596 $class->initialize(ref($_[0]) || $_[0]);
597 }) unless $options{no_meta};
599 $meta->superclasses(@{$options{superclasses}})
600 if exists $options{superclasses};
602 # process attributes first, so that they can
603 # install accessors, but locally defined methods
604 # can then overwrite them. It is maybe a little odd, but
605 # I think this should be the order of things.
606 if (exists $options{attributes}) {
607 foreach my $attr (@{$options{attributes}}) {
608 $meta->add_attribute($attr);
611 if (exists $options{methods}) {
612 foreach my $method_name (keys %{$options{methods}}) {
613 $meta->add_method($method_name, $options{methods}->{$method_name});
622 # all these attribute readers will be bootstrapped
623 # away in the Class::MOP bootstrap section
625 sub instance_metaclass { $_[0]->{'instance_metaclass'} }
626 sub immutable_trait { $_[0]->{'immutable_trait'} }
627 sub constructor_class { $_[0]->{'constructor_class'} }
628 sub constructor_name { $_[0]->{'constructor_name'} }
629 sub destructor_class { $_[0]->{'destructor_class'} }
631 # Instance Construction & Cloning
637 # we need to protect the integrity of the
638 # Class::MOP::Class singletons here, so we
639 # delegate this to &construct_class_instance
640 # which will deal with the singletons
641 return $class->_construct_class_instance(@_)
642 if $class->name->isa('Class::MOP::Class');
643 return $class->_construct_instance(@_);
646 sub _construct_instance {
648 my $params = @_ == 1 ? $_[0] : {@_};
649 my $meta_instance = $class->get_meta_instance();
651 # the code below is almost certainly incorrect
652 # but this is foreign inheritance, so we might
653 # have to kludge it in the end.
655 if (my $instance_class = blessed($params->{__INSTANCE__})) {
656 ($instance_class eq $class->name)
657 || confess "Objects passed as the __INSTANCE__ parameter must "
658 . "already be blessed into the correct class, but "
659 . "$params->{__INSTANCE__} is not a " . $class->name;
660 $instance = $params->{__INSTANCE__};
662 elsif (exists $params->{__INSTANCE__}) {
663 confess "The __INSTANCE__ parameter must be a blessed reference, not "
664 . $params->{__INSTANCE__};
667 $instance = $meta_instance->create_instance();
669 foreach my $attr ($class->get_all_attributes()) {
670 $attr->initialize_instance_slot($meta_instance, $instance, $params);
673 # this will only work for a HASH instance type
674 if ($class->is_anon_class) {
675 (reftype($instance) eq 'HASH')
676 || confess "Currently only HASH based instances are supported with instance of anon-classes";
678 # At some point we should make this official
679 # as a reserved slot name, but right now I am
680 # going to keep it here.
681 # my $RESERVED_MOP_SLOT = '__MOP__';
682 $instance->{'__MOP__'} = $class;
688 sub get_meta_instance {
690 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
693 sub _create_meta_instance {
696 my $instance = $self->instance_metaclass->new(
697 associated_metaclass => $self,
698 attributes => [ $self->get_all_attributes() ],
701 $self->add_meta_instance_dependencies()
702 if $instance->is_dependent_on_superclasses();
707 sub inline_create_instance {
710 return $self->get_meta_instance->inline_create_instance(@_);
713 sub inline_rebless_instance {
716 return $self->get_meta_instance->inline_rebless_instance_structure(@_);
721 my $instance = shift;
722 (blessed($instance) && $instance->isa($class->name))
723 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
726 # we need to protect the integrity of the
727 # Class::MOP::Class singletons here, they
728 # should not be cloned.
729 return $instance if $instance->isa('Class::MOP::Class');
730 $class->_clone_instance($instance, @_);
733 sub _clone_instance {
734 my ($class, $instance, %params) = @_;
736 || confess "You can only clone instances, ($instance) is not a blessed instance";
737 my $meta_instance = $class->get_meta_instance();
738 my $clone = $meta_instance->clone_instance($instance);
739 foreach my $attr ($class->get_all_attributes()) {
740 if ( defined( my $init_arg = $attr->init_arg ) ) {
741 if (exists $params{$init_arg}) {
742 $attr->set_value($clone, $params{$init_arg});
749 sub rebless_instance {
750 my ($self, $instance, %params) = @_;
752 my $old_metaclass = Class::MOP::class_of($instance);
754 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
755 $self->name->isa($old_class)
756 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
758 $old_metaclass->rebless_instance_away($instance, $self, %params)
761 my $meta_instance = $self->get_meta_instance();
764 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
765 $meta_instance->rebless_instance_structure($_[1], $self);
767 foreach my $attr ( $self->get_all_attributes ) {
768 if ( $attr->has_value($instance) ) {
769 if ( defined( my $init_arg = $attr->init_arg ) ) {
770 $params{$init_arg} = $attr->get_value($instance)
771 unless exists $params{$init_arg};
774 $attr->set_value($instance, $attr->get_value($instance));
779 foreach my $attr ($self->get_all_attributes) {
780 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
786 sub rebless_instance_back {
787 my ( $self, $instance ) = @_;
789 my $old_metaclass = Class::MOP::class_of($instance);
792 = $old_metaclass ? $old_metaclass->name : blessed($instance);
793 $old_class->isa( $self->name )
795 "You may rebless only into a superclass of ($old_class), of which ("
799 $old_metaclass->rebless_instance_away( $instance, $self )
802 my $meta_instance = $self->get_meta_instance;
804 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
805 $meta_instance->rebless_instance_structure( $_[1], $self );
807 for my $attr ( $old_metaclass->get_all_attributes ) {
808 next if $self->has_attribute( $attr->name );
809 $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
815 sub rebless_instance_away {
816 # this intentionally does nothing, it is just a hook
819 sub _attach_attribute {
820 my ($self, $attribute) = @_;
821 $attribute->attach_to_class($self);
824 sub _post_add_attribute {
825 my ( $self, $attribute ) = @_;
827 $self->invalidate_meta_instances;
829 # invalidate package flag here
832 $attribute->install_accessors;
835 $self->remove_attribute( $attribute->name );
840 sub remove_attribute {
843 my $removed_attribute = $self->SUPER::remove_attribute(@_)
846 $self->invalidate_meta_instances;
848 $removed_attribute->remove_accessors;
849 $removed_attribute->detach_from_class;
851 return$removed_attribute;
854 sub find_attribute_by_name {
855 my ( $self, $attr_name ) = @_;
857 foreach my $class ( $self->linearized_isa ) {
858 # fetch the meta-class ...
859 my $meta = Class::MOP::Class->initialize($class);
860 return $meta->get_attribute($attr_name)
861 if $meta->has_attribute($attr_name);
867 sub get_all_attributes {
869 my %attrs = map { %{ Class::MOP::Class->initialize($_)->_attribute_map } }
870 reverse $self->linearized_isa;
871 return values %attrs;
879 my $isa = $self->get_or_add_package_symbol(
880 { sigil => '@', type => 'ARRAY', name => 'ISA' } );
887 # on 5.8 and below, we need to call
888 # a method to get Perl to detect
889 # a cycle in the class hierarchy
890 my $class = $self->name;
894 # we need to check the metaclass
895 # compatibility here so that we can
896 # be sure that the superclass is
897 # not potentially creating an issues
898 # we don't know about
900 $self->_check_metaclass_compatibility();
901 $self->_superclasses_updated();
907 sub _superclasses_updated {
909 $self->update_meta_instance_dependencies();
914 my $super_class = $self->name;
916 return @{ $super_class->mro::get_isarev() };
919 sub direct_subclasses {
921 my $super_class = $self->name;
926 } Class::MOP::Class->initialize($_)->superclasses
931 return @{ mro::get_linear_isa( (shift)->name ) };
934 sub class_precedence_list {
936 my $name = $self->name;
938 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
940 # We need to check for circular inheritance here
941 # if we are are not on 5.10, cause 5.8 detects it
942 # late. This will do nothing if all is well, and
943 # blow up otherwise. Yes, it's an ugly hack, better
944 # suggestions are welcome.
946 ($name || return)->isa('This is a test for circular inheritance')
949 # if our mro is c3, we can
950 # just grab the linear_isa
951 if (mro::get_mro($name) eq 'c3') {
952 return @{ mro::get_linear_isa($name) }
956 # we can't grab the linear_isa for dfs
957 # since it has all the duplicates
962 Class::MOP::Class->initialize($_)->class_precedence_list()
963 } $self->superclasses()
971 my $fetch_and_prepare_method = sub {
972 my ($self, $method_name) = @_;
973 my $wrapped_metaclass = $self->wrapped_method_metaclass;
975 my $method = $self->get_method($method_name);
976 # if we dont have local ...
978 # try to find the next method
979 $method = $self->find_next_method_by_name($method_name);
980 # die if it does not exist
982 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
983 # and now make sure to wrap it
984 # even if it is already wrapped
985 # because we need a new sub ref
986 $method = $wrapped_metaclass->wrap($method,
987 package_name => $self->name,
988 name => $method_name,
992 # now make sure we wrap it properly
993 $method = $wrapped_metaclass->wrap($method,
994 package_name => $self->name,
995 name => $method_name,
996 ) unless $method->isa($wrapped_metaclass);
998 $self->add_method($method_name => $method);
1002 sub add_before_method_modifier {
1003 my ($self, $method_name, $method_modifier) = @_;
1004 (defined $method_name && length $method_name)
1005 || confess "You must pass in a method name";
1006 my $method = $fetch_and_prepare_method->($self, $method_name);
1007 $method->add_before_modifier(
1008 subname(':before' => $method_modifier)
1012 sub add_after_method_modifier {
1013 my ($self, $method_name, $method_modifier) = @_;
1014 (defined $method_name && length $method_name)
1015 || confess "You must pass in a method name";
1016 my $method = $fetch_and_prepare_method->($self, $method_name);
1017 $method->add_after_modifier(
1018 subname(':after' => $method_modifier)
1022 sub add_around_method_modifier {
1023 my ($self, $method_name, $method_modifier) = @_;
1024 (defined $method_name && length $method_name)
1025 || confess "You must pass in a method name";
1026 my $method = $fetch_and_prepare_method->($self, $method_name);
1027 $method->add_around_modifier(
1028 subname(':around' => $method_modifier)
1033 # the methods above used to be named like this:
1034 # ${pkg}::${method}:(before|after|around)
1035 # but this proved problematic when using one modifier
1036 # to wrap multiple methods (something which is likely
1037 # to happen pretty regularly IMO). So instead of naming
1038 # it like this, I have chosen to just name them purely
1039 # with their modifier names, like so:
1040 # :(before|after|around)
1041 # The fact is that in a stack trace, it will be fairly
1042 # evident from the context what method they are attached
1043 # to, and so don't need the fully qualified name.
1046 sub find_method_by_name {
1047 my ($self, $method_name) = @_;
1048 (defined $method_name && length $method_name)
1049 || confess "You must define a method name to find";
1050 foreach my $class ($self->linearized_isa) {
1051 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1052 return $method if defined $method;
1057 sub get_all_methods {
1061 for my $class ( reverse $self->linearized_isa ) {
1062 my $meta = Class::MOP::Class->initialize($class);
1064 $methods{ $_->name } = $_ for $meta->_get_local_methods;
1067 return values %methods;
1070 sub get_all_method_names {
1073 return grep { !$uniq{$_}++ } map { Class::MOP::Class->initialize($_)->get_method_list } $self->linearized_isa;
1076 sub find_all_methods_by_name {
1077 my ($self, $method_name) = @_;
1078 (defined $method_name && length $method_name)
1079 || confess "You must define a method name to find";
1081 foreach my $class ($self->linearized_isa) {
1082 # fetch the meta-class ...
1083 my $meta = Class::MOP::Class->initialize($class);
1085 name => $method_name,
1087 code => $meta->get_method($method_name)
1088 } if $meta->has_method($method_name);
1093 sub find_next_method_by_name {
1094 my ($self, $method_name) = @_;
1095 (defined $method_name && length $method_name)
1096 || confess "You must define a method name to find";
1097 my @cpl = $self->linearized_isa;
1098 shift @cpl; # discard ourselves
1099 foreach my $class (@cpl) {
1100 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1101 return $method if defined $method;
1106 sub update_meta_instance_dependencies {
1109 if ( $self->{meta_instance_dependencies} ) {
1110 return $self->add_meta_instance_dependencies;
1114 sub add_meta_instance_dependencies {
1117 $self->remove_meta_instance_dependencies;
1119 my @attrs = $self->get_all_attributes();
1122 my @classes = grep { not $seen{ $_->name }++ }
1123 map { $_->associated_class } @attrs;
1125 foreach my $class (@classes) {
1126 $class->add_dependent_meta_instance($self);
1129 $self->{meta_instance_dependencies} = \@classes;
1132 sub remove_meta_instance_dependencies {
1135 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
1136 foreach my $class (@$classes) {
1137 $class->remove_dependent_meta_instance($self);
1147 sub add_dependent_meta_instance {
1148 my ( $self, $metaclass ) = @_;
1149 push @{ $self->{dependent_meta_instances} }, $metaclass;
1152 sub remove_dependent_meta_instance {
1153 my ( $self, $metaclass ) = @_;
1154 my $name = $metaclass->name;
1155 @$_ = grep { $_->name ne $name } @$_
1156 for $self->{dependent_meta_instances};
1159 sub invalidate_meta_instances {
1161 $_->invalidate_meta_instance()
1162 for $self, @{ $self->{dependent_meta_instances} };
1165 sub invalidate_meta_instance {
1167 undef $self->{_meta_instance};
1170 # check if we can reinitialize
1174 # if any local attr is defined
1175 return if $self->get_attribute_list;
1177 # or any non-declared methods
1178 for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1179 return if $method->isa("Class::MOP::Method::Generated");
1180 # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1188 sub is_mutable { 1 }
1189 sub is_immutable { 0 }
1191 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1193 sub _immutable_options {
1194 my ( $self, @args ) = @_;
1197 inline_accessors => 1,
1198 inline_constructor => 1,
1199 inline_destructor => 0,
1201 immutable_trait => $self->immutable_trait,
1202 constructor_name => $self->constructor_name,
1203 constructor_class => $self->constructor_class,
1204 destructor_class => $self->destructor_class,
1209 sub make_immutable {
1210 my ( $self, @args ) = @_;
1212 if ( $self->is_mutable ) {
1213 $self->_initialize_immutable( $self->_immutable_options(@args) );
1214 $self->_rebless_as_immutable(@args);
1225 if ( $self->is_immutable ) {
1226 my @args = $self->immutable_options;
1227 $self->_rebless_as_mutable();
1228 $self->_remove_inlined_code(@args);
1229 delete $self->{__immutable};
1237 sub _rebless_as_immutable {
1238 my ( $self, @args ) = @_;
1240 $self->{__immutable}{original_class} = ref $self;
1242 bless $self => $self->_immutable_metaclass(@args);
1245 sub _immutable_metaclass {
1246 my ( $self, %args ) = @_;
1248 if ( my $class = $args{immutable_metaclass} ) {
1252 my $trait = $args{immutable_trait} = $self->immutable_trait
1253 || confess "no immutable trait specified for $self";
1255 my $meta = $self->meta;
1256 my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1260 if ( $meta_attr and $trait eq $meta_attr->default ) {
1261 # if the trait is the same as the default we try and pick a
1262 # predictable name for the immutable metaclass
1263 $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1266 $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1267 $trait, 'ForMetaClass', ref($self);
1271 if Class::MOP::is_class_loaded($class_name);
1273 # If the metaclass is a subclass of CMOP::Class which has had
1274 # metaclass roles applied (via Moose), then we want to make sure
1275 # that we preserve that anonymous class (see Fey::ORM for an
1276 # example of where this matters).
1277 my $meta_name = $meta->_real_ref_name;
1279 my $immutable_meta = $meta_name->create(
1281 superclasses => [ ref $self ],
1284 Class::MOP::MiniTrait::apply( $immutable_meta, $trait );
1286 $immutable_meta->make_immutable(
1287 inline_constructor => 0,
1288 inline_accessors => 0,
1294 sub _remove_inlined_code {
1297 $self->remove_method( $_->name ) for $self->_inlined_methods;
1299 delete $self->{__immutable}{inlined_methods};
1302 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1304 sub _add_inlined_method {
1305 my ( $self, $method ) = @_;
1307 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1310 sub _initialize_immutable {
1311 my ( $self, %args ) = @_;
1313 $self->{__immutable}{options} = \%args;
1314 $self->_install_inlined_code(%args);
1317 sub _install_inlined_code {
1318 my ( $self, %args ) = @_;
1321 $self->_inline_accessors(%args) if $args{inline_accessors};
1322 $self->_inline_constructor(%args) if $args{inline_constructor};
1323 $self->_inline_destructor(%args) if $args{inline_destructor};
1326 sub _rebless_as_mutable {
1329 bless $self, $self->_get_mutable_metaclass_name;
1334 sub _inline_accessors {
1337 foreach my $attr_name ( $self->get_attribute_list ) {
1338 $self->get_attribute($attr_name)->install_accessors(1);
1342 sub _inline_constructor {
1343 my ( $self, %args ) = @_;
1345 my $name = $args{constructor_name};
1346 # A class may not even have a constructor, and that's okay.
1347 return unless defined $name;
1349 if ( $self->has_method($name) && !$args{replace_constructor} ) {
1350 my $class = $self->name;
1351 warn "Not inlining a constructor for $class since it defines"
1352 . " its own constructor.\n"
1353 . "If you are certain you don't need to inline your"
1354 . " constructor, specify inline_constructor => 0 in your"
1355 . " call to $class->meta->make_immutable\n";
1359 my $constructor_class = $args{constructor_class};
1361 Class::MOP::load_class($constructor_class);
1363 my $constructor = $constructor_class->new(
1367 package_name => $self->name,
1371 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1372 $self->add_method( $name => $constructor );
1373 $self->_add_inlined_method($constructor);
1377 sub _inline_destructor {
1378 my ( $self, %args ) = @_;
1380 ( exists $args{destructor_class} && defined $args{destructor_class} )
1381 || confess "The 'inline_destructor' option is present, but "
1382 . "no destructor class was specified";
1384 if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1385 my $class = $self->name;
1386 warn "Not inlining a destructor for $class since it defines"
1387 . " its own destructor.\n";
1391 my $destructor_class = $args{destructor_class};
1393 Class::MOP::load_class($destructor_class);
1395 return unless $destructor_class->is_needed($self);
1397 my $destructor = $destructor_class->new(
1400 package_name => $self->name,
1404 if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1405 $self->add_method( 'DESTROY' => $destructor );
1406 $self->_add_inlined_method($destructor);
1418 Class::MOP::Class - Class Meta Object
1422 # assuming that class Foo
1423 # has been defined, you can
1425 # use this for introspection ...
1427 # add a method to Foo ...
1428 Foo->meta->add_method( 'bar' => sub {...} )
1430 # get a list of all the classes searched
1431 # the method dispatcher in the correct order
1432 Foo->meta->class_precedence_list()
1434 # remove a method from Foo
1435 Foo->meta->remove_method('bar');
1437 # or use this to actually create classes ...
1439 Class::MOP::Class->create(
1442 superclasses => ['Foo'],
1444 Class::MOP::Attribute->new('$bar'),
1445 Class::MOP::Attribute->new('$baz'),
1448 calculate_bar => sub {...},
1449 construct_baz => sub {...}
1456 The Class Protocol is the largest and most complex part of the
1457 Class::MOP meta-object protocol. It controls the introspection and
1458 manipulation of Perl 5 classes, and it can create them as well. The
1459 best way to understand what this module can do is to read the
1460 documentation for each of its methods.
1464 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1468 =head2 Class construction
1470 These methods all create new C<Class::MOP::Class> objects. These
1471 objects can represent existing classes or they can be used to create
1472 new classes from scratch.
1474 The metaclass object for a given class is a singleton. If you attempt
1475 to create a metaclass for the same class twice, you will just get the
1480 =item B<< Class::MOP::Class->create($package_name, %options) >>
1482 This method creates a new C<Class::MOP::Class> object with the given
1483 package name. It accepts a number of options:
1489 An optional version number for the newly created package.
1493 An optional authority for the newly created package.
1495 =item * superclasses
1497 An optional array reference of superclass names.
1501 An optional hash reference of methods for the class. The keys of the
1502 hash reference are method names and values are subroutine references.
1506 An optional array reference of L<Class::MOP::Attribute> objects.
1510 If true, a C<meta> method will not be installed into the class.
1514 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1516 This method works just like C<< Class::MOP::Class->create >> but it
1517 creates an "anonymous" class. In fact, the class does have a name, but
1518 that name is a unique name generated internally by this module.
1520 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1521 parameters that C<create> accepts.
1523 Anonymous classes are destroyed once the metaclass they are attached
1524 to goes out of scope, and will be removed from Perl's internal symbol
1527 All instances of an anonymous class keep a special reference to the
1528 metaclass object, which prevents the metaclass from going out of scope
1529 while any instances exist.
1531 This only works if the instance is based on a hash reference, however.
1533 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1535 This method will initialize a C<Class::MOP::Class> object for the
1536 named package. Unlike C<create>, this method I<will not> create a new
1539 The purpose of this method is to retrieve a C<Class::MOP::Class>
1540 object for introspecting an existing class.
1542 If an existing C<Class::MOP::Class> object exists for the named
1543 package, it will be returned, and any options provided will be
1546 If the object does not yet exist, it will be created.
1548 The valid options that can be passed to this method are
1549 C<attribute_metaclass>, C<method_metaclass>,
1550 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1551 optional, and default to the appropriate class in the C<Class::MOP>
1556 =head2 Object instance construction and cloning
1558 These methods are all related to creating and/or cloning object
1563 =item B<< $metaclass->clone_object($instance, %params) >>
1565 This method clones an existing object instance. Any parameters you
1566 provide are will override existing attribute values in the object.
1568 This is a convenience method for cloning an object instance, then
1569 blessing it into the appropriate package.
1571 You could implement a clone method in your class, using this method:
1574 my ($self, %params) = @_;
1575 $self->meta->clone_object($self, %params);
1578 =item B<< $metaclass->rebless_instance($instance, %params) >>
1580 This method changes the class of C<$instance> to the metaclass's class.
1582 You can only rebless an instance into a subclass of its current
1583 class. If you pass any additional parameters, these will be treated
1584 like constructor parameters and used to initialize the object's
1585 attributes. Any existing attributes that are already set will be
1588 Before reblessing the instance, this method will call
1589 C<rebless_instance_away> on the instance's current metaclass. This method
1590 will be passed the instance, the new metaclass, and any parameters
1591 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1592 does nothing; it is merely a hook.
1594 =item B<< $metaclass->rebless_instance_back($instance) >>
1596 Does the same thing as C<rebless_instance>, except that you can only
1597 rebless an instance into one of its superclasses. Any attributes that
1598 do not exist in the superclass will be deinitialized.
1600 This is a much more dangerous operation than C<rebless_instance>,
1601 especially when multiple inheritance is involved, so use this carefully!
1603 =item B<< $metaclass->new_object(%params) >>
1605 This method is used to create a new object of the metaclass's
1606 class. Any parameters you provide are used to initialize the
1607 instance's attributes. A special C<__INSTANCE__> key can be passed to
1608 provide an already generated instance, rather than having Class::MOP
1609 generate it for you. This is mostly useful for using Class::MOP with
1610 foreign classes which generate instances using their own constructors.
1612 =item B<< $metaclass->instance_metaclass >>
1614 Returns the class name of the instance metaclass. See
1615 L<Class::MOP::Instance> for more information on the instance
1618 =item B<< $metaclass->get_meta_instance >>
1620 Returns an instance of the C<instance_metaclass> to be used in the
1621 construction of a new instance of the class.
1623 =item B<< $metaclass->inline_create_instance($class_var) >>
1625 =item B<< $metaclass->inline_rebless_instance($instance_var, $class_var) >>
1627 These methods takes variable names, and use them to create an inline snippet
1628 of code that will create a new instance of the class.
1632 =head2 Informational predicates
1634 These are a few predicate methods for asking information about the
1639 =item B<< $metaclass->is_anon_class >>
1641 This returns true if the class was created by calling C<<
1642 Class::MOP::Class->create_anon_class >>.
1644 =item B<< $metaclass->is_mutable >>
1646 This returns true if the class is still mutable.
1648 =item B<< $metaclass->is_immutable >>
1650 This returns true if the class has been made immutable.
1652 =item B<< $metaclass->is_pristine >>
1654 A class is I<not> pristine if it has non-inherited attributes or if it
1655 has any generated methods.
1659 =head2 Inheritance Relationships
1663 =item B<< $metaclass->superclasses(@superclasses) >>
1665 This is a read-write accessor which represents the superclass
1666 relationships of the metaclass's class.
1668 This is basically sugar around getting and setting C<@ISA>.
1670 =item B<< $metaclass->class_precedence_list >>
1672 This returns a list of all of the class's ancestor classes. The
1673 classes are returned in method dispatch order.
1675 =item B<< $metaclass->linearized_isa >>
1677 This returns a list based on C<class_precedence_list> but with all
1680 =item B<< $metaclass->subclasses >>
1682 This returns a list of all subclasses for this class, even indirect
1685 =item B<< $metaclass->direct_subclasses >>
1687 This returns a list of immediate subclasses for this class, which does not
1688 include indirect subclasses.
1692 =head2 Method introspection and creation
1694 These methods allow you to introspect a class's methods, as well as
1695 add, remove, or change methods.
1697 Determining what is truly a method in a Perl 5 class requires some
1698 heuristics (aka guessing).
1700 Methods defined outside the package with a fully qualified name (C<sub
1701 Package::name { ... }>) will be included. Similarly, methods named
1702 with a fully qualified name using L<Sub::Name> are also included.
1704 However, we attempt to ignore imported functions.
1706 Ultimately, we are using heuristics to determine what truly is a
1707 method in a class, and these heuristics may get the wrong answer in
1708 some edge cases. However, for most "normal" cases the heuristics work
1713 =item B<< $metaclass->get_method($method_name) >>
1715 This will return a L<Class::MOP::Method> for the specified
1716 C<$method_name>. If the class does not have the specified method, it
1719 =item B<< $metaclass->has_method($method_name) >>
1721 Returns a boolean indicating whether or not the class defines the
1722 named method. It does not include methods inherited from parent
1725 =item B<< $metaclass->get_method_list >>
1727 This will return a list of method I<names> for all methods defined in
1730 =item B<< $metaclass->add_method($method_name, $method) >>
1732 This method takes a method name and a subroutine reference, and adds
1733 the method to the class.
1735 The subroutine reference can be a L<Class::MOP::Method>, and you are
1736 strongly encouraged to pass a meta method object instead of a code
1737 reference. If you do so, that object gets stored as part of the
1738 class's method map directly. If not, the meta information will have to
1739 be recreated later, and may be incorrect.
1741 If you provide a method object, this method will clone that object if
1742 the object's package name does not match the class name. This lets us
1743 track the original source of any methods added from other classes
1744 (notably Moose roles).
1746 =item B<< $metaclass->remove_method($method_name) >>
1748 Remove the named method from the class. This method returns the
1749 L<Class::MOP::Method> object for the method.
1751 =item B<< $metaclass->method_metaclass >>
1753 Returns the class name of the method metaclass, see
1754 L<Class::MOP::Method> for more information on the method metaclass.
1756 =item B<< $metaclass->wrapped_method_metaclass >>
1758 Returns the class name of the wrapped method metaclass, see
1759 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1762 =item B<< $metaclass->get_all_methods >>
1764 This will traverse the inheritance hierarchy and return a list of all
1765 the L<Class::MOP::Method> objects for this class and its parents.
1767 =item B<< $metaclass->find_method_by_name($method_name) >>
1769 This will return a L<Class::MOP::Method> for the specified
1770 C<$method_name>. If the class does not have the specified method, it
1773 Unlike C<get_method>, this method I<will> look for the named method in
1776 =item B<< $metaclass->get_all_method_names >>
1778 This will return a list of method I<names> for all of this class's
1779 methods, including inherited methods.
1781 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1783 This method looks for the named method in the class and all of its
1784 parents. It returns every matching method it finds in the inheritance
1785 tree, so it returns a list of methods.
1787 Each method is returned as a hash reference with three keys. The keys
1788 are C<name>, C<class>, and C<code>. The C<code> key has a
1789 L<Class::MOP::Method> object as its value.
1791 The list of methods is distinct.
1793 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1795 This method returns the first method in any superclass matching the
1796 given name. It is effectively the method that C<SUPER::$method_name>
1801 =head2 Attribute introspection and creation
1803 Because Perl 5 does not have a core concept of attributes in classes,
1804 we can only return information about attributes which have been added
1805 via this class's methods. We cannot discover information about
1806 attributes which are defined in terms of "regular" Perl 5 methods.
1810 =item B<< $metaclass->get_attribute($attribute_name) >>
1812 This will return a L<Class::MOP::Attribute> for the specified
1813 C<$attribute_name>. If the class does not have the specified
1814 attribute, it returns C<undef>.
1816 NOTE that get_attribute does not search superclasses, for that you
1817 need to use C<find_attribute_by_name>.
1819 =item B<< $metaclass->has_attribute($attribute_name) >>
1821 Returns a boolean indicating whether or not the class defines the
1822 named attribute. It does not include attributes inherited from parent
1825 =item B<< $metaclass->get_attribute_list >>
1827 This will return a list of attributes I<names> for all attributes
1828 defined in this class. Note that this operates on the current class
1829 only, it does not traverse the inheritance hierarchy.
1831 =item B<< $metaclass->get_all_attributes >>
1833 This will traverse the inheritance hierarchy and return a list of all
1834 the L<Class::MOP::Attribute> objects for this class and its parents.
1836 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1838 This will return a L<Class::MOP::Attribute> for the specified
1839 C<$attribute_name>. If the class does not have the specified
1840 attribute, it returns C<undef>.
1842 Unlike C<get_attribute>, this attribute I<will> look for the named
1843 attribute in superclasses.
1845 =item B<< $metaclass->add_attribute(...) >>
1847 This method accepts either an existing L<Class::MOP::Attribute>
1848 object or parameters suitable for passing to that class's C<new>
1851 The attribute provided will be added to the class.
1853 Any accessor methods defined by the attribute will be added to the
1854 class when the attribute is added.
1856 If an attribute of the same name already exists, the old attribute
1857 will be removed first.
1859 =item B<< $metaclass->remove_attribute($attribute_name) >>
1861 This will remove the named attribute from the class, and
1862 L<Class::MOP::Attribute> object.
1864 Removing an attribute also removes any accessor methods defined by the
1867 However, note that removing an attribute will only affect I<future>
1868 object instances created for this class, not existing instances.
1870 =item B<< $metaclass->attribute_metaclass >>
1872 Returns the class name of the attribute metaclass for this class. By
1873 default, this is L<Class::MOP::Attribute>.
1877 =head2 Class Immutability
1879 Making a class immutable "freezes" the class definition. You can no
1880 longer call methods which alter the class, such as adding or removing
1881 methods or attributes.
1883 Making a class immutable lets us optimize the class by inlining some
1884 methods, and also allows us to optimize some methods on the metaclass
1887 After immutabilization, the metaclass object will cache most informational
1888 methods that returns information about methods or attributes. Methods which
1889 would alter the class, such as C<add_attribute> and C<add_method>, will
1890 throw an error on an immutable metaclass object.
1892 The immutabilization system in L<Moose> takes much greater advantage
1893 of the inlining features than Class::MOP itself does.
1897 =item B<< $metaclass->make_immutable(%options) >>
1899 This method will create an immutable transformer and use it to make
1900 the class and its metaclass object immutable.
1902 This method accepts the following options:
1906 =item * inline_accessors
1908 =item * inline_constructor
1910 =item * inline_destructor
1912 These are all booleans indicating whether the specified method(s)
1915 By default, accessors and the constructor are inlined, but not the
1918 =item * immutable_trait
1920 The name of a class which will be used as a parent class for the
1921 metaclass object being made immutable. This "trait" implements the
1922 post-immutability functionality of the metaclass (but not the
1923 transformation itself).
1925 This defaults to L<Class::MOP::Class::Immutable::Trait>.
1927 =item * constructor_name
1929 This is the constructor method name. This defaults to "new".
1931 =item * constructor_class
1933 The name of the method metaclass for constructors. It will be used to
1934 generate the inlined constructor. This defaults to
1935 "Class::MOP::Method::Constructor".
1937 =item * replace_constructor
1939 This is a boolean indicating whether an existing constructor should be
1940 replaced when inlining a constructor. This defaults to false.
1942 =item * destructor_class
1944 The name of the method metaclass for destructors. It will be used to
1945 generate the inlined destructor. This defaults to
1946 "Class::MOP::Method::Denstructor".
1948 =item * replace_destructor
1950 This is a boolean indicating whether an existing destructor should be
1951 replaced when inlining a destructor. This defaults to false.
1955 =item B<< $metaclass->immutable_options >>
1957 Returns a hash of the options used when making the class immutable, including
1958 both defaults and anything supplied by the user in the call to C<<
1959 $metaclass->make_immutable >>. This is useful if you need to temporarily make
1960 a class mutable and then restore immutability as it was before.
1962 =item B<< $metaclass->make_mutable >>
1964 Calling this method reverse the immutabilization transformation.
1968 =head2 Method Modifiers
1970 Method modifiers are hooks which allow a method to be wrapped with
1971 I<before>, I<after> and I<around> method modifiers. Every time a
1972 method is called, its modifiers are also called.
1974 A class can modify its own methods, as well as methods defined in
1977 =head3 How method modifiers work?
1979 Method modifiers work by wrapping the original method and then
1980 replacing it in the class's symbol table. The wrappers will handle
1981 calling all the modifiers in the appropriate order and preserving the
1982 calling context for the original method.
1984 The return values of C<before> and C<after> modifiers are
1985 ignored. This is because their purpose is B<not> to filter the input
1986 and output of the primary method (this is done with an I<around>
1989 This may seem like an odd restriction to some, but doing this allows
1990 for simple code to be added at the beginning or end of a method call
1991 without altering the function of the wrapped method or placing any
1992 extra responsibility on the code of the modifier.
1994 Of course if you have more complex needs, you can use the C<around>
1995 modifier which allows you to change both the parameters passed to the
1996 wrapped method, as well as its return value.
1998 Before and around modifiers are called in last-defined-first-called
1999 order, while after modifiers are called in first-defined-first-called
2000 order. So the call tree might looks something like this:
2012 =head3 What is the performance impact?
2014 Of course there is a performance cost associated with method
2015 modifiers, but we have made every effort to make that cost directly
2016 proportional to the number of modifier features you use.
2018 The wrapping method does its best to B<only> do as much work as it
2019 absolutely needs to. In order to do this we have moved some of the
2020 performance costs to set-up time, where they are easier to amortize.
2022 All this said, our benchmarks have indicated the following:
2024 simple wrapper with no modifiers 100% slower
2025 simple wrapper with simple before modifier 400% slower
2026 simple wrapper with simple after modifier 450% slower
2027 simple wrapper with simple around modifier 500-550% slower
2028 simple wrapper with all 3 modifiers 1100% slower
2030 These numbers may seem daunting, but you must remember, every feature
2031 comes with some cost. To put things in perspective, just doing a
2032 simple C<AUTOLOAD> which does nothing but extract the name of the
2033 method called and return it costs about 400% over a normal method
2038 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
2040 This wraps the specified method with the supplied subroutine
2041 reference. The modifier will be called as a method itself, and will
2042 receive the same arguments as are passed to the method.
2044 When the modifier exits, the wrapped method will be called.
2046 The return value of the modifier will be ignored.
2048 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
2050 This wraps the specified method with the supplied subroutine
2051 reference. The modifier will be called as a method itself, and will
2052 receive the same arguments as are passed to the method.
2054 When the wrapped methods exits, the modifier will be called.
2056 The return value of the modifier will be ignored.
2058 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
2060 This wraps the specified method with the supplied subroutine
2063 The first argument passed to the modifier will be a subroutine
2064 reference to the wrapped method. The second argument is the object,
2065 and after that come any arguments passed when the method is called.
2067 The around modifier can choose to call the original method, as well as
2068 what arguments to pass if it does so.
2070 The return value of the modifier is what will be seen by the caller.
2074 =head2 Introspection
2078 =item B<< Class::MOP::Class->meta >>
2080 This will return a L<Class::MOP::Class> instance for this class.
2082 It should also be noted that L<Class::MOP> will actually bootstrap
2083 this module by installing a number of attribute meta-objects into its
2090 Stevan Little E<lt>stevan@iinteractive.comE<gt>
2092 =head1 COPYRIGHT AND LICENSE
2094 Copyright 2006-2010 by Infinity Interactive, Inc.
2096 L<http://www.iinteractive.com>
2098 This library is free software; you can redistribute it and/or modify
2099 it under the same terms as Perl itself.