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 $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 _class_metaclass_is_compatible {
240 my ( $superclass_name ) = @_;
242 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
245 my $super_meta_type = $super_meta->_real_ref_name;
247 return $self->isa($super_meta_type);
250 sub _check_class_metaclass_compatibility {
252 my ( $superclass_name ) = @_;
254 if (!$self->_class_metaclass_is_compatible($superclass_name)) {
255 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
257 my $super_meta_type = $super_meta->_real_ref_name;
259 confess "The metaclass of " . $self->name . " ("
260 . (ref($self)) . ")" . " is not compatible with "
261 . "the metaclass of its superclass, "
262 . $superclass_name . " (" . ($super_meta_type) . ")";
266 sub _single_metaclass_is_compatible {
268 my ( $metaclass_type, $superclass_name ) = @_;
270 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
273 # for instance, Moose::Meta::Class has a error_class attribute, but
274 # Class::MOP::Class doesn't - this shouldn't be an error
275 return 1 unless $super_meta->can($metaclass_type);
276 # for instance, Moose::Meta::Class has a destructor_class, but
277 # Class::MOP::Class doesn't - this shouldn't be an error
278 return 1 unless defined $super_meta->$metaclass_type;
279 # if metaclass is defined in superclass but not here, it's not compatible
280 # this is a really odd case
281 return 0 unless defined $self->$metaclass_type;
283 return $self->$metaclass_type->isa($super_meta->$metaclass_type);
286 sub _check_single_metaclass_compatibility {
288 my ( $metaclass_type, $superclass_name ) = @_;
290 if (!$self->_single_metaclass_is_compatible($metaclass_type, $superclass_name)) {
291 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
292 my $metaclass_type_name = $metaclass_type;
293 $metaclass_type_name =~ s/_(?:meta)?class$//;
294 $metaclass_type_name =~ s/_/ /g;
295 confess "The $metaclass_type_name metaclass for "
296 . $self->name . " (" . ($self->$metaclass_type)
297 . ")" . " is not compatible with the "
298 . "$metaclass_type_name metaclass of its "
299 . "superclass, $superclass_name ("
300 . ($super_meta->$metaclass_type) . ")";
304 sub _can_fix_class_metaclass_incompatibility_by_subclassing {
306 my ($super_meta) = @_;
308 my $super_meta_type = $super_meta->_real_ref_name;
310 return $super_meta_type ne blessed($self)
311 && $super_meta->isa(blessed($self));
314 sub _can_fix_single_metaclass_incompatibility_by_subclassing {
316 my ($metaclass_type, $super_meta) = @_;
318 my $specific_meta = $self->$metaclass_type;
319 return unless $super_meta->can($metaclass_type);
320 my $super_specific_meta = $super_meta->$metaclass_type;
322 # for instance, Moose::Meta::Class has a destructor_class, but
323 # Class::MOP::Class doesn't - this shouldn't be an error
324 return unless defined $super_specific_meta;
326 # if metaclass is defined in superclass but not here, it's fixable
327 # this is a really odd case
328 return 1 unless defined $specific_meta;
330 return $specific_meta ne $super_specific_meta
331 && $super_specific_meta->isa($specific_meta);
334 sub _can_fix_metaclass_incompatibility_by_subclassing {
336 my ($super_meta) = @_;
338 return 1 if $self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta);
340 my %base_metaclass = $self->_base_metaclasses;
341 for my $metaclass_type (keys %base_metaclass) {
342 return 1 if $self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta);
348 sub _can_fix_metaclass_incompatibility {
350 return $self->_can_fix_metaclass_incompatibility_by_subclassing(@_);
353 sub _fix_metaclass_incompatibility {
355 my @supers = map { Class::MOP::Class->initialize($_) } @_;
358 for my $super (@supers) {
360 if $self->_can_fix_metaclass_incompatibility($super);
362 return unless $necessary;
364 for my $super (@supers) {
365 if (!$self->_class_metaclass_is_compatible($super->name)) {
366 $self->_fix_class_metaclass_incompatibility($super);
370 my %base_metaclass = $self->_base_metaclasses;
371 for my $metaclass_type (keys %base_metaclass) {
372 for my $super (@supers) {
373 if (!$self->_single_metaclass_is_compatible($metaclass_type, $super->name)) {
374 $self->_fix_single_metaclass_incompatibility(
375 $metaclass_type, $super
382 sub _fix_class_metaclass_incompatibility {
384 my ( $super_meta ) = @_;
386 if ($self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta)) {
388 || confess "Can't fix metaclass incompatibility for "
390 . " because it is not pristine.";
392 my $super_meta_name = $super_meta->_real_ref_name;
394 $super_meta_name->meta->rebless_instance($self);
398 sub _fix_single_metaclass_incompatibility {
400 my ( $metaclass_type, $super_meta ) = @_;
402 if ($self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta)) {
404 || confess "Can't fix metaclass incompatibility for "
406 . " because it is not pristine.";
408 $self->{$metaclass_type} = $super_meta->$metaclass_type;
412 sub _get_associated_single_metaclass {
414 my ($single_meta_name) = @_;
416 my $current_single_meta_name;
417 if ($single_meta_name->isa('Class::MOP::Method')) {
418 $current_single_meta_name = $self->method_metaclass;
420 elsif ($single_meta_name->isa('Class::MOP::Attribute')) {
421 $current_single_meta_name = $self->attribute_metaclass;
424 confess "Can't make $single_meta_name compatible, it isn't an "
425 . "attribute or method metaclass.";
428 return $current_single_meta_name;
431 sub _get_compatible_single_metaclass_by_subclassing {
433 my ($single_meta_name) = @_;
435 my $current_single_meta_name = $self->_get_associated_single_metaclass($single_meta_name);
437 if ($single_meta_name->isa($current_single_meta_name)) {
438 return $single_meta_name;
440 elsif ($current_single_meta_name->isa($single_meta_name)) {
441 return $current_single_meta_name;
447 sub _get_compatible_single_metaclass {
449 my ($single_meta_name) = @_;
451 return $self->_get_compatible_single_metaclass_by_subclassing($single_meta_name);
454 sub _make_metaobject_compatible {
458 my $new_metaclass = $self->_get_compatible_single_metaclass(blessed($object));
460 if (!defined($new_metaclass)) {
461 confess "Can't make $object compatible with metaclass "
462 . $self->_get_associated_single_metaclass(blessed($object));
465 # can't use rebless_instance here, because it might not be an actual
466 # subclass in the case of, e.g. moose role reconciliation
467 $new_metaclass->meta->_force_rebless_instance($object)
468 if blessed($object) ne $new_metaclass;
473 sub _restore_metaobjects_from {
477 for my $method ($old_meta->_get_local_methods) {
478 $self->_make_metaobject_compatible($method);
479 $self->add_method($method->name => $method);
482 for my $attr (sort { $a->insertion_order <=> $b->insertion_order }
483 map { $old_meta->get_attribute($_) }
484 $old_meta->get_attribute_list) {
485 $self->_make_metaobject_compatible($attr);
486 $self->add_attribute($attr);
490 sub _remove_generated_metaobjects {
493 for my $attr (map { $self->get_attribute($_) } $self->get_attribute_list) {
494 $attr->remove_accessors;
502 # this should be sufficient, if you have a
503 # use case where it is not, write a test and
505 my $ANON_CLASS_SERIAL = 0;
508 # we need a sufficiently annoying prefix
509 # this should suffice for now, this is
510 # used in a couple of places below, so
511 # need to put it up here for now.
512 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
516 no warnings 'uninitialized';
517 $self->name =~ /^$ANON_CLASS_PREFIX/o;
520 sub create_anon_class {
521 my ($class, %options) = @_;
522 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
523 return $class->create($package_name, %options);
527 # this will only get called for
528 # anon-classes, all other calls
529 # are assumed to occur during
530 # global destruction and so don't
531 # really need to be handled explicitly
535 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
537 no warnings 'uninitialized';
538 my $name = $self->name;
539 return unless $name =~ /^$ANON_CLASS_PREFIX/o;
541 # Moose does a weird thing where it replaces the metaclass for
542 # class when fixing metaclass incompatibility. In that case,
543 # we don't want to clean out the namespace now. We can detect
544 # that because Moose will explicitly update the singleton
545 # cache in Class::MOP.
546 my $current_meta = Class::MOP::get_metaclass_by_name($name);
547 return if $current_meta ne $self;
549 my ($serial_id) = ($name =~ /^$ANON_CLASS_PREFIX(\d+)/o);
551 @{$name . '::ISA'} = ();
552 %{$name . '::'} = ();
553 delete ${$ANON_CLASS_PREFIX}{$serial_id . '::'};
555 Class::MOP::remove_metaclass_by_name($name);
560 # creating classes with MOP ...
563 my ( $class, @args ) = @_;
565 unshift @args, 'package' if @args % 2 == 1;
567 my (%options) = @args;
568 my $package_name = $options{package};
570 (ref $options{superclasses} eq 'ARRAY')
571 || confess "You must pass an ARRAY ref of superclasses"
572 if exists $options{superclasses};
574 (ref $options{attributes} eq 'ARRAY')
575 || confess "You must pass an ARRAY ref of attributes"
576 if exists $options{attributes};
578 (ref $options{methods} eq 'HASH')
579 || confess "You must pass a HASH ref of methods"
580 if exists $options{methods};
582 my (%initialize_options) = @args;
583 delete @initialize_options{qw(
592 my $meta = $class->initialize( $package_name => %initialize_options );
594 $meta->_instantiate_module( $options{version}, $options{authority} );
597 $meta->add_method('meta' => sub {
598 if (Class::MOP::DEBUG_NO_META()) {
600 if (my $meta = try { $self->SUPER::meta }) {
601 return $meta if $meta->isa('Class::MOP::Class');
603 confess "'meta' method called by MOP internals"
604 if caller =~ /Class::MOP|metaclass/;
606 $class->initialize(ref($_[0]) || $_[0]);
607 }) unless $options{no_meta};
609 $meta->superclasses(@{$options{superclasses}})
610 if exists $options{superclasses};
612 # process attributes first, so that they can
613 # install accessors, but locally defined methods
614 # can then overwrite them. It is maybe a little odd, but
615 # I think this should be the order of things.
616 if (exists $options{attributes}) {
617 foreach my $attr (@{$options{attributes}}) {
618 $meta->add_attribute($attr);
621 if (exists $options{methods}) {
622 foreach my $method_name (keys %{$options{methods}}) {
623 $meta->add_method($method_name, $options{methods}->{$method_name});
632 # all these attribute readers will be bootstrapped
633 # away in the Class::MOP bootstrap section
635 sub instance_metaclass { $_[0]->{'instance_metaclass'} }
636 sub immutable_trait { $_[0]->{'immutable_trait'} }
637 sub constructor_class { $_[0]->{'constructor_class'} }
638 sub constructor_name { $_[0]->{'constructor_name'} }
639 sub destructor_class { $_[0]->{'destructor_class'} }
641 # Instance Construction & Cloning
647 # we need to protect the integrity of the
648 # Class::MOP::Class singletons here, so we
649 # delegate this to &construct_class_instance
650 # which will deal with the singletons
651 return $class->_construct_class_instance(@_)
652 if $class->name->isa('Class::MOP::Class');
653 return $class->_construct_instance(@_);
656 sub _construct_instance {
658 my $params = @_ == 1 ? $_[0] : {@_};
659 my $meta_instance = $class->get_meta_instance();
661 # the code below is almost certainly incorrect
662 # but this is foreign inheritance, so we might
663 # have to kludge it in the end.
665 if (my $instance_class = blessed($params->{__INSTANCE__})) {
666 ($instance_class eq $class->name)
667 || confess "Objects passed as the __INSTANCE__ parameter must "
668 . "already be blessed into the correct class, but "
669 . "$params->{__INSTANCE__} is not a " . $class->name;
670 $instance = $params->{__INSTANCE__};
672 elsif (exists $params->{__INSTANCE__}) {
673 confess "The __INSTANCE__ parameter must be a blessed reference, not "
674 . $params->{__INSTANCE__};
677 $instance = $meta_instance->create_instance();
679 foreach my $attr ($class->get_all_attributes()) {
680 $attr->initialize_instance_slot($meta_instance, $instance, $params);
683 # this will only work for a HASH instance type
684 if ($class->is_anon_class) {
685 (reftype($instance) eq 'HASH')
686 || confess "Currently only HASH based instances are supported with instance of anon-classes";
688 # At some point we should make this official
689 # as a reserved slot name, but right now I am
690 # going to keep it here.
691 # my $RESERVED_MOP_SLOT = '__MOP__';
692 $instance->{'__MOP__'} = $class;
698 sub get_meta_instance {
700 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
703 sub _create_meta_instance {
706 my $instance = $self->instance_metaclass->new(
707 associated_metaclass => $self,
708 attributes => [ $self->get_all_attributes() ],
711 $self->add_meta_instance_dependencies()
712 if $instance->is_dependent_on_superclasses();
717 sub inline_create_instance {
720 return $self->get_meta_instance->inline_create_instance(@_);
723 sub inline_rebless_instance {
726 return $self->get_meta_instance->inline_rebless_instance_structure(@_);
731 my $instance = shift;
732 (blessed($instance) && $instance->isa($class->name))
733 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
736 # we need to protect the integrity of the
737 # Class::MOP::Class singletons here, they
738 # should not be cloned.
739 return $instance if $instance->isa('Class::MOP::Class');
740 $class->_clone_instance($instance, @_);
743 sub _clone_instance {
744 my ($class, $instance, %params) = @_;
746 || confess "You can only clone instances, ($instance) is not a blessed instance";
747 my $meta_instance = $class->get_meta_instance();
748 my $clone = $meta_instance->clone_instance($instance);
749 foreach my $attr ($class->get_all_attributes()) {
750 if ( defined( my $init_arg = $attr->init_arg ) ) {
751 if (exists $params{$init_arg}) {
752 $attr->set_value($clone, $params{$init_arg});
759 sub _force_rebless_instance {
760 my ($self, $instance, %params) = @_;
761 my $old_metaclass = Class::MOP::class_of($instance);
763 $old_metaclass->rebless_instance_away($instance, $self, %params)
766 my $meta_instance = $self->get_meta_instance;
769 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
770 $meta_instance->rebless_instance_structure($_[1], $self);
772 $self->_fixup_attributes_after_rebless($instance, $old_metaclass, %params);
775 sub rebless_instance {
776 my ($self, $instance, %params) = @_;
777 my $old_metaclass = Class::MOP::class_of($instance);
779 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
780 $self->name->isa($old_class)
781 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
783 $self->_force_rebless_instance($_[1], %params);
788 sub rebless_instance_back {
789 my ( $self, $instance ) = @_;
790 my $old_metaclass = Class::MOP::class_of($instance);
793 = $old_metaclass ? $old_metaclass->name : blessed($instance);
794 $old_class->isa( $self->name )
796 "You may rebless only into a superclass of ($old_class), of which ("
800 $self->_force_rebless_instance($_[1]);
805 sub rebless_instance_away {
806 # this intentionally does nothing, it is just a hook
809 sub _fixup_attributes_after_rebless {
811 my ($instance, $rebless_from, %params) = @_;
812 my $meta_instance = $self->get_meta_instance;
814 for my $attr ( $rebless_from->get_all_attributes ) {
815 next if $self->find_attribute_by_name( $attr->name );
816 $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
819 foreach my $attr ( $self->get_all_attributes ) {
820 if ( $attr->has_value($instance) ) {
821 if ( defined( my $init_arg = $attr->init_arg ) ) {
822 $params{$init_arg} = $attr->get_value($instance)
823 unless exists $params{$init_arg};
826 $attr->set_value($instance, $attr->get_value($instance));
831 foreach my $attr ($self->get_all_attributes) {
832 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
836 sub _attach_attribute {
837 my ($self, $attribute) = @_;
838 $attribute->attach_to_class($self);
841 sub _post_add_attribute {
842 my ( $self, $attribute ) = @_;
844 $self->invalidate_meta_instances;
846 # invalidate package flag here
849 $attribute->install_accessors;
852 $self->remove_attribute( $attribute->name );
857 sub remove_attribute {
860 my $removed_attribute = $self->SUPER::remove_attribute(@_)
863 $self->invalidate_meta_instances;
865 $removed_attribute->remove_accessors;
866 $removed_attribute->detach_from_class;
868 return$removed_attribute;
871 sub find_attribute_by_name {
872 my ( $self, $attr_name ) = @_;
874 foreach my $class ( $self->linearized_isa ) {
875 # fetch the meta-class ...
876 my $meta = Class::MOP::Class->initialize($class);
877 return $meta->get_attribute($attr_name)
878 if $meta->has_attribute($attr_name);
884 sub get_all_attributes {
886 my %attrs = map { %{ Class::MOP::Class->initialize($_)->_attribute_map } }
887 reverse $self->linearized_isa;
888 return values %attrs;
896 my $isa = $self->get_or_add_package_symbol(
897 { sigil => '@', type => 'ARRAY', name => 'ISA' } );
904 # on 5.8 and below, we need to call
905 # a method to get Perl to detect
906 # a cycle in the class hierarchy
907 my $class = $self->name;
911 # we need to check the metaclass
912 # compatibility here so that we can
913 # be sure that the superclass is
914 # not potentially creating an issues
915 # we don't know about
917 $self->_check_metaclass_compatibility();
918 $self->_superclasses_updated();
924 sub _superclasses_updated {
926 $self->update_meta_instance_dependencies();
931 my $super_class = $self->name;
933 return @{ $super_class->mro::get_isarev() };
936 sub direct_subclasses {
938 my $super_class = $self->name;
943 } Class::MOP::Class->initialize($_)->superclasses
948 return @{ mro::get_linear_isa( (shift)->name ) };
951 sub class_precedence_list {
953 my $name = $self->name;
955 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
957 # We need to check for circular inheritance here
958 # if we are are not on 5.10, cause 5.8 detects it
959 # late. This will do nothing if all is well, and
960 # blow up otherwise. Yes, it's an ugly hack, better
961 # suggestions are welcome.
963 ($name || return)->isa('This is a test for circular inheritance')
966 # if our mro is c3, we can
967 # just grab the linear_isa
968 if (mro::get_mro($name) eq 'c3') {
969 return @{ mro::get_linear_isa($name) }
973 # we can't grab the linear_isa for dfs
974 # since it has all the duplicates
979 Class::MOP::Class->initialize($_)->class_precedence_list()
980 } $self->superclasses()
988 my $fetch_and_prepare_method = sub {
989 my ($self, $method_name) = @_;
990 my $wrapped_metaclass = $self->wrapped_method_metaclass;
992 my $method = $self->get_method($method_name);
993 # if we dont have local ...
995 # try to find the next method
996 $method = $self->find_next_method_by_name($method_name);
997 # die if it does not exist
999 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
1000 # and now make sure to wrap it
1001 # even if it is already wrapped
1002 # because we need a new sub ref
1003 $method = $wrapped_metaclass->wrap($method,
1004 package_name => $self->name,
1005 name => $method_name,
1009 # now make sure we wrap it properly
1010 $method = $wrapped_metaclass->wrap($method,
1011 package_name => $self->name,
1012 name => $method_name,
1013 ) unless $method->isa($wrapped_metaclass);
1015 $self->add_method($method_name => $method);
1019 sub add_before_method_modifier {
1020 my ($self, $method_name, $method_modifier) = @_;
1021 (defined $method_name && length $method_name)
1022 || confess "You must pass in a method name";
1023 my $method = $fetch_and_prepare_method->($self, $method_name);
1024 $method->add_before_modifier(
1025 subname(':before' => $method_modifier)
1029 sub add_after_method_modifier {
1030 my ($self, $method_name, $method_modifier) = @_;
1031 (defined $method_name && length $method_name)
1032 || confess "You must pass in a method name";
1033 my $method = $fetch_and_prepare_method->($self, $method_name);
1034 $method->add_after_modifier(
1035 subname(':after' => $method_modifier)
1039 sub add_around_method_modifier {
1040 my ($self, $method_name, $method_modifier) = @_;
1041 (defined $method_name && length $method_name)
1042 || confess "You must pass in a method name";
1043 my $method = $fetch_and_prepare_method->($self, $method_name);
1044 $method->add_around_modifier(
1045 subname(':around' => $method_modifier)
1050 # the methods above used to be named like this:
1051 # ${pkg}::${method}:(before|after|around)
1052 # but this proved problematic when using one modifier
1053 # to wrap multiple methods (something which is likely
1054 # to happen pretty regularly IMO). So instead of naming
1055 # it like this, I have chosen to just name them purely
1056 # with their modifier names, like so:
1057 # :(before|after|around)
1058 # The fact is that in a stack trace, it will be fairly
1059 # evident from the context what method they are attached
1060 # to, and so don't need the fully qualified name.
1063 sub find_method_by_name {
1064 my ($self, $method_name) = @_;
1065 (defined $method_name && length $method_name)
1066 || confess "You must define a method name to find";
1067 foreach my $class ($self->linearized_isa) {
1068 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1069 return $method if defined $method;
1074 sub get_all_methods {
1078 for my $class ( reverse $self->linearized_isa ) {
1079 my $meta = Class::MOP::Class->initialize($class);
1081 $methods{ $_->name } = $_ for $meta->_get_local_methods;
1084 return values %methods;
1087 sub get_all_method_names {
1090 return grep { !$uniq{$_}++ } map { Class::MOP::Class->initialize($_)->get_method_list } $self->linearized_isa;
1093 sub find_all_methods_by_name {
1094 my ($self, $method_name) = @_;
1095 (defined $method_name && length $method_name)
1096 || confess "You must define a method name to find";
1098 foreach my $class ($self->linearized_isa) {
1099 # fetch the meta-class ...
1100 my $meta = Class::MOP::Class->initialize($class);
1102 name => $method_name,
1104 code => $meta->get_method($method_name)
1105 } if $meta->has_method($method_name);
1110 sub find_next_method_by_name {
1111 my ($self, $method_name) = @_;
1112 (defined $method_name && length $method_name)
1113 || confess "You must define a method name to find";
1114 my @cpl = $self->linearized_isa;
1115 shift @cpl; # discard ourselves
1116 foreach my $class (@cpl) {
1117 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1118 return $method if defined $method;
1123 sub update_meta_instance_dependencies {
1126 if ( $self->{meta_instance_dependencies} ) {
1127 return $self->add_meta_instance_dependencies;
1131 sub add_meta_instance_dependencies {
1134 $self->remove_meta_instance_dependencies;
1136 my @attrs = $self->get_all_attributes();
1139 my @classes = grep { not $seen{ $_->name }++ }
1140 map { $_->associated_class } @attrs;
1142 foreach my $class (@classes) {
1143 $class->add_dependent_meta_instance($self);
1146 $self->{meta_instance_dependencies} = \@classes;
1149 sub remove_meta_instance_dependencies {
1152 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
1153 foreach my $class (@$classes) {
1154 $class->remove_dependent_meta_instance($self);
1164 sub add_dependent_meta_instance {
1165 my ( $self, $metaclass ) = @_;
1166 push @{ $self->{dependent_meta_instances} }, $metaclass;
1169 sub remove_dependent_meta_instance {
1170 my ( $self, $metaclass ) = @_;
1171 my $name = $metaclass->name;
1172 @$_ = grep { $_->name ne $name } @$_
1173 for $self->{dependent_meta_instances};
1176 sub invalidate_meta_instances {
1178 $_->invalidate_meta_instance()
1179 for $self, @{ $self->{dependent_meta_instances} };
1182 sub invalidate_meta_instance {
1184 undef $self->{_meta_instance};
1187 # check if we can reinitialize
1191 # if any local attr is defined
1192 return if $self->get_attribute_list;
1194 # or any non-declared methods
1195 for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1196 return if $method->isa("Class::MOP::Method::Generated");
1197 # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1205 sub is_mutable { 1 }
1206 sub is_immutable { 0 }
1208 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1210 sub _immutable_options {
1211 my ( $self, @args ) = @_;
1214 inline_accessors => 1,
1215 inline_constructor => 1,
1216 inline_destructor => 0,
1218 immutable_trait => $self->immutable_trait,
1219 constructor_name => $self->constructor_name,
1220 constructor_class => $self->constructor_class,
1221 destructor_class => $self->destructor_class,
1226 sub make_immutable {
1227 my ( $self, @args ) = @_;
1229 if ( $self->is_mutable ) {
1230 $self->_initialize_immutable( $self->_immutable_options(@args) );
1231 $self->_rebless_as_immutable(@args);
1242 if ( $self->is_immutable ) {
1243 my @args = $self->immutable_options;
1244 $self->_rebless_as_mutable();
1245 $self->_remove_inlined_code(@args);
1246 delete $self->{__immutable};
1254 sub _rebless_as_immutable {
1255 my ( $self, @args ) = @_;
1257 $self->{__immutable}{original_class} = ref $self;
1259 bless $self => $self->_immutable_metaclass(@args);
1262 sub _immutable_metaclass {
1263 my ( $self, %args ) = @_;
1265 if ( my $class = $args{immutable_metaclass} ) {
1269 my $trait = $args{immutable_trait} = $self->immutable_trait
1270 || confess "no immutable trait specified for $self";
1272 my $meta = $self->meta;
1273 my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1277 if ( $meta_attr and $trait eq $meta_attr->default ) {
1278 # if the trait is the same as the default we try and pick a
1279 # predictable name for the immutable metaclass
1280 $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1283 $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1284 $trait, 'ForMetaClass', ref($self);
1288 if Class::MOP::is_class_loaded($class_name);
1290 # If the metaclass is a subclass of CMOP::Class which has had
1291 # metaclass roles applied (via Moose), then we want to make sure
1292 # that we preserve that anonymous class (see Fey::ORM for an
1293 # example of where this matters).
1294 my $meta_name = $meta->_real_ref_name;
1296 my $immutable_meta = $meta_name->create(
1298 superclasses => [ ref $self ],
1301 Class::MOP::MiniTrait::apply( $immutable_meta, $trait );
1303 $immutable_meta->make_immutable(
1304 inline_constructor => 0,
1305 inline_accessors => 0,
1311 sub _remove_inlined_code {
1314 $self->remove_method( $_->name ) for $self->_inlined_methods;
1316 delete $self->{__immutable}{inlined_methods};
1319 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1321 sub _add_inlined_method {
1322 my ( $self, $method ) = @_;
1324 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1327 sub _initialize_immutable {
1328 my ( $self, %args ) = @_;
1330 $self->{__immutable}{options} = \%args;
1331 $self->_install_inlined_code(%args);
1334 sub _install_inlined_code {
1335 my ( $self, %args ) = @_;
1338 $self->_inline_accessors(%args) if $args{inline_accessors};
1339 $self->_inline_constructor(%args) if $args{inline_constructor};
1340 $self->_inline_destructor(%args) if $args{inline_destructor};
1343 sub _rebless_as_mutable {
1346 bless $self, $self->_get_mutable_metaclass_name;
1351 sub _inline_accessors {
1354 foreach my $attr_name ( $self->get_attribute_list ) {
1355 $self->get_attribute($attr_name)->install_accessors(1);
1359 sub _inline_constructor {
1360 my ( $self, %args ) = @_;
1362 my $name = $args{constructor_name};
1363 # A class may not even have a constructor, and that's okay.
1364 return unless defined $name;
1366 if ( $self->has_method($name) && !$args{replace_constructor} ) {
1367 my $class = $self->name;
1368 warn "Not inlining a constructor for $class since it defines"
1369 . " its own constructor.\n"
1370 . "If you are certain you don't need to inline your"
1371 . " constructor, specify inline_constructor => 0 in your"
1372 . " call to $class->meta->make_immutable\n";
1376 my $constructor_class = $args{constructor_class};
1378 Class::MOP::load_class($constructor_class);
1380 my $constructor = $constructor_class->new(
1384 package_name => $self->name,
1388 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1389 $self->add_method( $name => $constructor );
1390 $self->_add_inlined_method($constructor);
1394 sub _inline_destructor {
1395 my ( $self, %args ) = @_;
1397 ( exists $args{destructor_class} && defined $args{destructor_class} )
1398 || confess "The 'inline_destructor' option is present, but "
1399 . "no destructor class was specified";
1401 if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1402 my $class = $self->name;
1403 warn "Not inlining a destructor for $class since it defines"
1404 . " its own destructor.\n";
1408 my $destructor_class = $args{destructor_class};
1410 Class::MOP::load_class($destructor_class);
1412 return unless $destructor_class->is_needed($self);
1414 my $destructor = $destructor_class->new(
1417 package_name => $self->name,
1421 if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1422 $self->add_method( 'DESTROY' => $destructor );
1423 $self->_add_inlined_method($destructor);
1435 Class::MOP::Class - Class Meta Object
1439 # assuming that class Foo
1440 # has been defined, you can
1442 # use this for introspection ...
1444 # add a method to Foo ...
1445 Foo->meta->add_method( 'bar' => sub {...} )
1447 # get a list of all the classes searched
1448 # the method dispatcher in the correct order
1449 Foo->meta->class_precedence_list()
1451 # remove a method from Foo
1452 Foo->meta->remove_method('bar');
1454 # or use this to actually create classes ...
1456 Class::MOP::Class->create(
1459 superclasses => ['Foo'],
1461 Class::MOP::Attribute->new('$bar'),
1462 Class::MOP::Attribute->new('$baz'),
1465 calculate_bar => sub {...},
1466 construct_baz => sub {...}
1473 The Class Protocol is the largest and most complex part of the
1474 Class::MOP meta-object protocol. It controls the introspection and
1475 manipulation of Perl 5 classes, and it can create them as well. The
1476 best way to understand what this module can do is to read the
1477 documentation for each of its methods.
1481 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1485 =head2 Class construction
1487 These methods all create new C<Class::MOP::Class> objects. These
1488 objects can represent existing classes or they can be used to create
1489 new classes from scratch.
1491 The metaclass object for a given class is a singleton. If you attempt
1492 to create a metaclass for the same class twice, you will just get the
1497 =item B<< Class::MOP::Class->create($package_name, %options) >>
1499 This method creates a new C<Class::MOP::Class> object with the given
1500 package name. It accepts a number of options:
1506 An optional version number for the newly created package.
1510 An optional authority for the newly created package.
1512 =item * superclasses
1514 An optional array reference of superclass names.
1518 An optional hash reference of methods for the class. The keys of the
1519 hash reference are method names and values are subroutine references.
1523 An optional array reference of L<Class::MOP::Attribute> objects.
1527 If true, a C<meta> method will not be installed into the class.
1531 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1533 This method works just like C<< Class::MOP::Class->create >> but it
1534 creates an "anonymous" class. In fact, the class does have a name, but
1535 that name is a unique name generated internally by this module.
1537 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1538 parameters that C<create> accepts.
1540 Anonymous classes are destroyed once the metaclass they are attached
1541 to goes out of scope, and will be removed from Perl's internal symbol
1544 All instances of an anonymous class keep a special reference to the
1545 metaclass object, which prevents the metaclass from going out of scope
1546 while any instances exist.
1548 This only works if the instance is based on a hash reference, however.
1550 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1552 This method will initialize a C<Class::MOP::Class> object for the
1553 named package. Unlike C<create>, this method I<will not> create a new
1556 The purpose of this method is to retrieve a C<Class::MOP::Class>
1557 object for introspecting an existing class.
1559 If an existing C<Class::MOP::Class> object exists for the named
1560 package, it will be returned, and any options provided will be
1563 If the object does not yet exist, it will be created.
1565 The valid options that can be passed to this method are
1566 C<attribute_metaclass>, C<method_metaclass>,
1567 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1568 optional, and default to the appropriate class in the C<Class::MOP>
1573 =head2 Object instance construction and cloning
1575 These methods are all related to creating and/or cloning object
1580 =item B<< $metaclass->clone_object($instance, %params) >>
1582 This method clones an existing object instance. Any parameters you
1583 provide are will override existing attribute values in the object.
1585 This is a convenience method for cloning an object instance, then
1586 blessing it into the appropriate package.
1588 You could implement a clone method in your class, using this method:
1591 my ($self, %params) = @_;
1592 $self->meta->clone_object($self, %params);
1595 =item B<< $metaclass->rebless_instance($instance, %params) >>
1597 This method changes the class of C<$instance> to the metaclass's class.
1599 You can only rebless an instance into a subclass of its current
1600 class. If you pass any additional parameters, these will be treated
1601 like constructor parameters and used to initialize the object's
1602 attributes. Any existing attributes that are already set will be
1605 Before reblessing the instance, this method will call
1606 C<rebless_instance_away> on the instance's current metaclass. This method
1607 will be passed the instance, the new metaclass, and any parameters
1608 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1609 does nothing; it is merely a hook.
1611 =item B<< $metaclass->rebless_instance_back($instance) >>
1613 Does the same thing as C<rebless_instance>, except that you can only
1614 rebless an instance into one of its superclasses. Any attributes that
1615 do not exist in the superclass will be deinitialized.
1617 This is a much more dangerous operation than C<rebless_instance>,
1618 especially when multiple inheritance is involved, so use this carefully!
1620 =item B<< $metaclass->new_object(%params) >>
1622 This method is used to create a new object of the metaclass's
1623 class. Any parameters you provide are used to initialize the
1624 instance's attributes. A special C<__INSTANCE__> key can be passed to
1625 provide an already generated instance, rather than having Class::MOP
1626 generate it for you. This is mostly useful for using Class::MOP with
1627 foreign classes which generate instances using their own constructors.
1629 =item B<< $metaclass->instance_metaclass >>
1631 Returns the class name of the instance metaclass. See
1632 L<Class::MOP::Instance> for more information on the instance
1635 =item B<< $metaclass->get_meta_instance >>
1637 Returns an instance of the C<instance_metaclass> to be used in the
1638 construction of a new instance of the class.
1640 =item B<< $metaclass->inline_create_instance($class_var) >>
1642 =item B<< $metaclass->inline_rebless_instance($instance_var, $class_var) >>
1644 These methods takes variable names, and use them to create an inline snippet
1645 of code that will create a new instance of the class.
1649 =head2 Informational predicates
1651 These are a few predicate methods for asking information about the
1656 =item B<< $metaclass->is_anon_class >>
1658 This returns true if the class was created by calling C<<
1659 Class::MOP::Class->create_anon_class >>.
1661 =item B<< $metaclass->is_mutable >>
1663 This returns true if the class is still mutable.
1665 =item B<< $metaclass->is_immutable >>
1667 This returns true if the class has been made immutable.
1669 =item B<< $metaclass->is_pristine >>
1671 A class is I<not> pristine if it has non-inherited attributes or if it
1672 has any generated methods.
1676 =head2 Inheritance Relationships
1680 =item B<< $metaclass->superclasses(@superclasses) >>
1682 This is a read-write accessor which represents the superclass
1683 relationships of the metaclass's class.
1685 This is basically sugar around getting and setting C<@ISA>.
1687 =item B<< $metaclass->class_precedence_list >>
1689 This returns a list of all of the class's ancestor classes. The
1690 classes are returned in method dispatch order.
1692 =item B<< $metaclass->linearized_isa >>
1694 This returns a list based on C<class_precedence_list> but with all
1697 =item B<< $metaclass->subclasses >>
1699 This returns a list of all subclasses for this class, even indirect
1702 =item B<< $metaclass->direct_subclasses >>
1704 This returns a list of immediate subclasses for this class, which does not
1705 include indirect subclasses.
1709 =head2 Method introspection and creation
1711 These methods allow you to introspect a class's methods, as well as
1712 add, remove, or change methods.
1714 Determining what is truly a method in a Perl 5 class requires some
1715 heuristics (aka guessing).
1717 Methods defined outside the package with a fully qualified name (C<sub
1718 Package::name { ... }>) will be included. Similarly, methods named
1719 with a fully qualified name using L<Sub::Name> are also included.
1721 However, we attempt to ignore imported functions.
1723 Ultimately, we are using heuristics to determine what truly is a
1724 method in a class, and these heuristics may get the wrong answer in
1725 some edge cases. However, for most "normal" cases the heuristics work
1730 =item B<< $metaclass->get_method($method_name) >>
1732 This will return a L<Class::MOP::Method> for the specified
1733 C<$method_name>. If the class does not have the specified method, it
1736 =item B<< $metaclass->has_method($method_name) >>
1738 Returns a boolean indicating whether or not the class defines the
1739 named method. It does not include methods inherited from parent
1742 =item B<< $metaclass->get_method_list >>
1744 This will return a list of method I<names> for all methods defined in
1747 =item B<< $metaclass->add_method($method_name, $method) >>
1749 This method takes a method name and a subroutine reference, and adds
1750 the method to the class.
1752 The subroutine reference can be a L<Class::MOP::Method>, and you are
1753 strongly encouraged to pass a meta method object instead of a code
1754 reference. If you do so, that object gets stored as part of the
1755 class's method map directly. If not, the meta information will have to
1756 be recreated later, and may be incorrect.
1758 If you provide a method object, this method will clone that object if
1759 the object's package name does not match the class name. This lets us
1760 track the original source of any methods added from other classes
1761 (notably Moose roles).
1763 =item B<< $metaclass->remove_method($method_name) >>
1765 Remove the named method from the class. This method returns the
1766 L<Class::MOP::Method> object for the method.
1768 =item B<< $metaclass->method_metaclass >>
1770 Returns the class name of the method metaclass, see
1771 L<Class::MOP::Method> for more information on the method metaclass.
1773 =item B<< $metaclass->wrapped_method_metaclass >>
1775 Returns the class name of the wrapped method metaclass, see
1776 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1779 =item B<< $metaclass->get_all_methods >>
1781 This will traverse the inheritance hierarchy and return a list of all
1782 the L<Class::MOP::Method> objects for this class and its parents.
1784 =item B<< $metaclass->find_method_by_name($method_name) >>
1786 This will return a L<Class::MOP::Method> for the specified
1787 C<$method_name>. If the class does not have the specified method, it
1790 Unlike C<get_method>, this method I<will> look for the named method in
1793 =item B<< $metaclass->get_all_method_names >>
1795 This will return a list of method I<names> for all of this class's
1796 methods, including inherited methods.
1798 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1800 This method looks for the named method in the class and all of its
1801 parents. It returns every matching method it finds in the inheritance
1802 tree, so it returns a list of methods.
1804 Each method is returned as a hash reference with three keys. The keys
1805 are C<name>, C<class>, and C<code>. The C<code> key has a
1806 L<Class::MOP::Method> object as its value.
1808 The list of methods is distinct.
1810 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1812 This method returns the first method in any superclass matching the
1813 given name. It is effectively the method that C<SUPER::$method_name>
1818 =head2 Attribute introspection and creation
1820 Because Perl 5 does not have a core concept of attributes in classes,
1821 we can only return information about attributes which have been added
1822 via this class's methods. We cannot discover information about
1823 attributes which are defined in terms of "regular" Perl 5 methods.
1827 =item B<< $metaclass->get_attribute($attribute_name) >>
1829 This will return a L<Class::MOP::Attribute> for the specified
1830 C<$attribute_name>. If the class does not have the specified
1831 attribute, it returns C<undef>.
1833 NOTE that get_attribute does not search superclasses, for that you
1834 need to use C<find_attribute_by_name>.
1836 =item B<< $metaclass->has_attribute($attribute_name) >>
1838 Returns a boolean indicating whether or not the class defines the
1839 named attribute. It does not include attributes inherited from parent
1842 =item B<< $metaclass->get_attribute_list >>
1844 This will return a list of attributes I<names> for all attributes
1845 defined in this class. Note that this operates on the current class
1846 only, it does not traverse the inheritance hierarchy.
1848 =item B<< $metaclass->get_all_attributes >>
1850 This will traverse the inheritance hierarchy and return a list of all
1851 the L<Class::MOP::Attribute> objects for this class and its parents.
1853 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1855 This will return a L<Class::MOP::Attribute> for the specified
1856 C<$attribute_name>. If the class does not have the specified
1857 attribute, it returns C<undef>.
1859 Unlike C<get_attribute>, this attribute I<will> look for the named
1860 attribute in superclasses.
1862 =item B<< $metaclass->add_attribute(...) >>
1864 This method accepts either an existing L<Class::MOP::Attribute>
1865 object or parameters suitable for passing to that class's C<new>
1868 The attribute provided will be added to the class.
1870 Any accessor methods defined by the attribute will be added to the
1871 class when the attribute is added.
1873 If an attribute of the same name already exists, the old attribute
1874 will be removed first.
1876 =item B<< $metaclass->remove_attribute($attribute_name) >>
1878 This will remove the named attribute from the class, and
1879 L<Class::MOP::Attribute> object.
1881 Removing an attribute also removes any accessor methods defined by the
1884 However, note that removing an attribute will only affect I<future>
1885 object instances created for this class, not existing instances.
1887 =item B<< $metaclass->attribute_metaclass >>
1889 Returns the class name of the attribute metaclass for this class. By
1890 default, this is L<Class::MOP::Attribute>.
1894 =head2 Class Immutability
1896 Making a class immutable "freezes" the class definition. You can no
1897 longer call methods which alter the class, such as adding or removing
1898 methods or attributes.
1900 Making a class immutable lets us optimize the class by inlining some
1901 methods, and also allows us to optimize some methods on the metaclass
1904 After immutabilization, the metaclass object will cache most informational
1905 methods that returns information about methods or attributes. Methods which
1906 would alter the class, such as C<add_attribute> and C<add_method>, will
1907 throw an error on an immutable metaclass object.
1909 The immutabilization system in L<Moose> takes much greater advantage
1910 of the inlining features than Class::MOP itself does.
1914 =item B<< $metaclass->make_immutable(%options) >>
1916 This method will create an immutable transformer and use it to make
1917 the class and its metaclass object immutable.
1919 This method accepts the following options:
1923 =item * inline_accessors
1925 =item * inline_constructor
1927 =item * inline_destructor
1929 These are all booleans indicating whether the specified method(s)
1932 By default, accessors and the constructor are inlined, but not the
1935 =item * immutable_trait
1937 The name of a class which will be used as a parent class for the
1938 metaclass object being made immutable. This "trait" implements the
1939 post-immutability functionality of the metaclass (but not the
1940 transformation itself).
1942 This defaults to L<Class::MOP::Class::Immutable::Trait>.
1944 =item * constructor_name
1946 This is the constructor method name. This defaults to "new".
1948 =item * constructor_class
1950 The name of the method metaclass for constructors. It will be used to
1951 generate the inlined constructor. This defaults to
1952 "Class::MOP::Method::Constructor".
1954 =item * replace_constructor
1956 This is a boolean indicating whether an existing constructor should be
1957 replaced when inlining a constructor. This defaults to false.
1959 =item * destructor_class
1961 The name of the method metaclass for destructors. It will be used to
1962 generate the inlined destructor. This defaults to
1963 "Class::MOP::Method::Denstructor".
1965 =item * replace_destructor
1967 This is a boolean indicating whether an existing destructor should be
1968 replaced when inlining a destructor. This defaults to false.
1972 =item B<< $metaclass->immutable_options >>
1974 Returns a hash of the options used when making the class immutable, including
1975 both defaults and anything supplied by the user in the call to C<<
1976 $metaclass->make_immutable >>. This is useful if you need to temporarily make
1977 a class mutable and then restore immutability as it was before.
1979 =item B<< $metaclass->make_mutable >>
1981 Calling this method reverse the immutabilization transformation.
1985 =head2 Method Modifiers
1987 Method modifiers are hooks which allow a method to be wrapped with
1988 I<before>, I<after> and I<around> method modifiers. Every time a
1989 method is called, its modifiers are also called.
1991 A class can modify its own methods, as well as methods defined in
1994 =head3 How method modifiers work?
1996 Method modifiers work by wrapping the original method and then
1997 replacing it in the class's symbol table. The wrappers will handle
1998 calling all the modifiers in the appropriate order and preserving the
1999 calling context for the original method.
2001 The return values of C<before> and C<after> modifiers are
2002 ignored. This is because their purpose is B<not> to filter the input
2003 and output of the primary method (this is done with an I<around>
2006 This may seem like an odd restriction to some, but doing this allows
2007 for simple code to be added at the beginning or end of a method call
2008 without altering the function of the wrapped method or placing any
2009 extra responsibility on the code of the modifier.
2011 Of course if you have more complex needs, you can use the C<around>
2012 modifier which allows you to change both the parameters passed to the
2013 wrapped method, as well as its return value.
2015 Before and around modifiers are called in last-defined-first-called
2016 order, while after modifiers are called in first-defined-first-called
2017 order. So the call tree might looks something like this:
2029 =head3 What is the performance impact?
2031 Of course there is a performance cost associated with method
2032 modifiers, but we have made every effort to make that cost directly
2033 proportional to the number of modifier features you use.
2035 The wrapping method does its best to B<only> do as much work as it
2036 absolutely needs to. In order to do this we have moved some of the
2037 performance costs to set-up time, where they are easier to amortize.
2039 All this said, our benchmarks have indicated the following:
2041 simple wrapper with no modifiers 100% slower
2042 simple wrapper with simple before modifier 400% slower
2043 simple wrapper with simple after modifier 450% slower
2044 simple wrapper with simple around modifier 500-550% slower
2045 simple wrapper with all 3 modifiers 1100% slower
2047 These numbers may seem daunting, but you must remember, every feature
2048 comes with some cost. To put things in perspective, just doing a
2049 simple C<AUTOLOAD> which does nothing but extract the name of the
2050 method called and return it costs about 400% over a normal method
2055 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
2057 This wraps the specified method with the supplied subroutine
2058 reference. The modifier will be called as a method itself, and will
2059 receive the same arguments as are passed to the method.
2061 When the modifier exits, the wrapped method will be called.
2063 The return value of the modifier will be ignored.
2065 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
2067 This wraps the specified method with the supplied subroutine
2068 reference. The modifier will be called as a method itself, and will
2069 receive the same arguments as are passed to the method.
2071 When the wrapped methods exits, the modifier will be called.
2073 The return value of the modifier will be ignored.
2075 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
2077 This wraps the specified method with the supplied subroutine
2080 The first argument passed to the modifier will be a subroutine
2081 reference to the wrapped method. The second argument is the object,
2082 and after that come any arguments passed when the method is called.
2084 The around modifier can choose to call the original method, as well as
2085 what arguments to pass if it does so.
2087 The return value of the modifier is what will be seen by the caller.
2091 =head2 Introspection
2095 =item B<< Class::MOP::Class->meta >>
2097 This will return a L<Class::MOP::Class> instance for this class.
2099 It should also be noted that L<Class::MOP> will actually bootstrap
2100 this module by installing a number of attribute meta-objects into its
2107 Stevan Little E<lt>stevan@iinteractive.comE<gt>
2109 =head1 COPYRIGHT AND LICENSE
2111 Copyright 2006-2010 by Infinity Interactive, Inc.
2113 L<http://www.iinteractive.com>
2115 This library is free software; you can redistribute it and/or modify
2116 it under the same terms as Perl itself.