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.11';
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 $options{weaken} = Class::MOP::metaclass_is_weak($old_metaclass->name)
57 if !exists $options{weaken}
58 && blessed($old_metaclass)
59 && $old_metaclass->isa('Class::MOP::Class');
60 $old_metaclass->_remove_generated_metaobjects
61 if $old_metaclass && $old_metaclass->isa('Class::MOP::Class');
62 my $new_metaclass = $class->SUPER::reinitialize(%options);
63 $new_metaclass->_restore_metaobjects_from($old_metaclass)
64 if $old_metaclass && $old_metaclass->isa('Class::MOP::Class');
65 return $new_metaclass;
68 # NOTE: (meta-circularity)
69 # this is a special form of _construct_instance
70 # (see below), which is used to construct class
71 # meta-object instances for any Class::MOP::*
72 # class. All other classes will use the more
73 # normal &construct_instance.
74 sub _construct_class_instance {
76 my $options = @_ == 1 ? $_[0] : {@_};
77 my $package_name = $options->{package};
78 (defined $package_name && $package_name)
79 || confess "You must pass a package name";
81 # return the metaclass if we have it cached,
82 # and it is still defined (it has not been
83 # reaped by DESTROY yet, which can happen
84 # annoyingly enough during global destruction)
86 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
92 ? $class->_real_ref_name
95 # now create the metaclass
97 if ($class eq 'Class::MOP::Class') {
98 $meta = $class->_new($options);
102 # it is safe to use meta here because
103 # class will always be a subclass of
104 # Class::MOP::Class, which defines meta
105 $meta = $class->meta->_construct_instance($options)
108 # and check the metaclass compatibility
109 $meta->_check_metaclass_compatibility();
111 Class::MOP::store_metaclass_by_name($package_name, $meta);
114 # we need to weaken any anon classes
115 # so that they can call DESTROY properly
116 Class::MOP::weaken_metaclass($package_name) if $options->{weaken};
124 # NOTE: we need to deal with the possibility of class immutability here,
125 # and then get the name of the class appropriately
126 return $self->is_immutable
127 ? $self->_get_mutable_metaclass_name()
134 return Class::MOP::Class->initialize($class)->new_object(@_)
135 if $class ne __PACKAGE__;
137 my $options = @_ == 1 ? $_[0] : {@_};
140 # inherited from Class::MOP::Package
141 'package' => $options->{package},
144 # since the following attributes will
145 # actually be loaded from the symbol
146 # table, and actually bypass the instance
147 # entirely, we can just leave these things
148 # listed here for reference, because they
149 # should not actually have a value associated
151 'namespace' => \undef,
154 # inherited from Class::MOP::Module
156 'authority' => \undef,
158 # defined in Class::MOP::Class
159 'superclasses' => \undef,
162 'attribute_metaclass' =>
163 ( $options->{'attribute_metaclass'} || 'Class::MOP::Attribute' ),
164 'method_metaclass' =>
165 ( $options->{'method_metaclass'} || 'Class::MOP::Method' ),
166 'wrapped_method_metaclass' => (
167 $options->{'wrapped_method_metaclass'}
168 || 'Class::MOP::Method::Wrapped'
170 'instance_metaclass' =>
171 ( $options->{'instance_metaclass'} || 'Class::MOP::Instance' ),
172 'immutable_trait' => (
173 $options->{'immutable_trait'}
174 || 'Class::MOP::Class::Immutable::Trait'
176 'constructor_name' => ( $options->{constructor_name} || 'new' ),
177 'constructor_class' => (
178 $options->{constructor_class} || 'Class::MOP::Method::Constructor'
180 'destructor_class' => $options->{destructor_class},
184 ## Metaclass compatibility
186 my %base_metaclass = (
187 attribute_metaclass => 'Class::MOP::Attribute',
188 method_metaclass => 'Class::MOP::Method',
189 wrapped_method_metaclass => 'Class::MOP::Method::Wrapped',
190 instance_metaclass => 'Class::MOP::Instance',
191 constructor_class => 'Class::MOP::Method::Constructor',
192 destructor_class => 'Class::MOP::Method::Destructor',
195 sub _base_metaclasses { %base_metaclass }
198 sub _check_metaclass_compatibility {
201 my @superclasses = $self->superclasses
204 $self->_fix_metaclass_incompatibility(@superclasses);
206 my %base_metaclass = $self->_base_metaclasses;
208 # this is always okay ...
210 if ref($self) eq 'Class::MOP::Class'
212 my $meta = $self->$_;
213 !defined($meta) || $meta eq $base_metaclass{$_};
215 keys %base_metaclass;
217 for my $superclass (@superclasses) {
218 $self->_check_class_metaclass_compatibility($superclass);
221 for my $metaclass_type ( keys %base_metaclass ) {
222 next unless defined $self->$metaclass_type;
223 for my $superclass (@superclasses) {
224 $self->_check_single_metaclass_compatibility( $metaclass_type,
230 sub _check_class_metaclass_compatibility {
232 my ( $superclass_name ) = @_;
234 if (!$self->_class_metaclass_is_compatible($superclass_name)) {
235 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
237 my $super_meta_type = $super_meta->_real_ref_name;
239 confess "The metaclass of " . $self->name . " ("
240 . (ref($self)) . ")" . " is not compatible with "
241 . "the metaclass of its superclass, "
242 . $superclass_name . " (" . ($super_meta_type) . ")";
246 sub _class_metaclass_is_compatible {
248 my ( $superclass_name ) = @_;
250 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
253 my $super_meta_name = $super_meta->_real_ref_name;
255 return $self->_is_compatible_with($super_meta_name);
258 sub _check_single_metaclass_compatibility {
260 my ( $metaclass_type, $superclass_name ) = @_;
262 if (!$self->_single_metaclass_is_compatible($metaclass_type, $superclass_name)) {
263 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
264 my $metaclass_type_name = $metaclass_type;
265 $metaclass_type_name =~ s/_(?:meta)?class$//;
266 $metaclass_type_name =~ s/_/ /g;
267 confess "The $metaclass_type_name metaclass for "
268 . $self->name . " (" . ($self->$metaclass_type)
269 . ")" . " is not compatible with the "
270 . "$metaclass_type_name metaclass of its "
271 . "superclass, $superclass_name ("
272 . ($super_meta->$metaclass_type) . ")";
276 sub _single_metaclass_is_compatible {
278 my ( $metaclass_type, $superclass_name ) = @_;
280 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
283 # for instance, Moose::Meta::Class has a error_class attribute, but
284 # Class::MOP::Class doesn't - this shouldn't be an error
285 return 1 unless $super_meta->can($metaclass_type);
286 # for instance, Moose::Meta::Class has a destructor_class, but
287 # Class::MOP::Class doesn't - this shouldn't be an error
288 return 1 unless defined $super_meta->$metaclass_type;
289 # if metaclass is defined in superclass but not here, it's not compatible
290 # this is a really odd case
291 return 0 unless defined $self->$metaclass_type;
293 return $self->$metaclass_type->_is_compatible_with($super_meta->$metaclass_type);
296 sub _fix_metaclass_incompatibility {
298 my @supers = map { Class::MOP::Class->initialize($_) } @_;
301 for my $super (@supers) {
303 if $self->_can_fix_metaclass_incompatibility($super);
305 return unless $necessary;
307 for my $super (@supers) {
308 if (!$self->_class_metaclass_is_compatible($super->name)) {
309 $self->_fix_class_metaclass_incompatibility($super);
313 my %base_metaclass = $self->_base_metaclasses;
314 for my $metaclass_type (keys %base_metaclass) {
315 for my $super (@supers) {
316 if (!$self->_single_metaclass_is_compatible($metaclass_type, $super->name)) {
317 $self->_fix_single_metaclass_incompatibility(
318 $metaclass_type, $super
325 sub _can_fix_metaclass_incompatibility {
327 my ($super_meta) = @_;
329 return 1 if $self->_class_metaclass_can_be_made_compatible($super_meta);
331 my %base_metaclass = $self->_base_metaclasses;
332 for my $metaclass_type (keys %base_metaclass) {
333 return 1 if $self->_single_metaclass_can_be_made_compatible($super_meta, $metaclass_type);
339 sub _class_metaclass_can_be_made_compatible {
341 my ($super_meta) = @_;
343 return $self->_can_be_made_compatible_with($super_meta->_real_ref_name);
346 sub _single_metaclass_can_be_made_compatible {
348 my ($super_meta, $metaclass_type) = @_;
350 my $specific_meta = $self->$metaclass_type;
352 return unless $super_meta->can($metaclass_type);
353 my $super_specific_meta = $super_meta->$metaclass_type;
355 # for instance, Moose::Meta::Class has a destructor_class, but
356 # Class::MOP::Class doesn't - this shouldn't be an error
357 return unless defined $super_specific_meta;
359 # if metaclass is defined in superclass but not here, it's fixable
360 # this is a really odd case
361 return 1 unless defined $specific_meta;
363 return 1 if $specific_meta->_can_be_made_compatible_with($super_specific_meta);
366 sub _fix_class_metaclass_incompatibility {
368 my ( $super_meta ) = @_;
370 if ($self->_class_metaclass_can_be_made_compatible($super_meta)) {
372 || confess "Can't fix metaclass incompatibility for "
374 . " because it is not pristine.";
376 my $super_meta_name = $super_meta->_real_ref_name;
378 $self->_make_compatible_with($super_meta_name);
382 sub _fix_single_metaclass_incompatibility {
384 my ( $metaclass_type, $super_meta ) = @_;
386 if ($self->_single_metaclass_can_be_made_compatible($super_meta, $metaclass_type)) {
388 || confess "Can't fix metaclass incompatibility for "
390 . " because it is not pristine.";
392 my $new_metaclass = $self->$metaclass_type
393 ? $self->$metaclass_type->_get_compatible_metaclass($super_meta->$metaclass_type)
394 : $super_meta->$metaclass_type;
395 $self->{$metaclass_type} = $new_metaclass;
399 sub _restore_metaobjects_from {
403 $self->_restore_metamethods_from($old_meta);
404 $self->_restore_metaattributes_from($old_meta);
407 sub _remove_generated_metaobjects {
410 for my $attr (map { $self->get_attribute($_) } $self->get_attribute_list) {
411 $attr->remove_accessors;
419 # this should be sufficient, if you have a
420 # use case where it is not, write a test and
422 my $ANON_CLASS_SERIAL = 0;
425 # we need a sufficiently annoying prefix
426 # this should suffice for now, this is
427 # used in a couple of places below, so
428 # need to put it up here for now.
429 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
433 no warnings 'uninitialized';
434 $self->name =~ /^$ANON_CLASS_PREFIX/o;
437 sub create_anon_class {
438 my ($class, %options) = @_;
439 $options{weaken} = 1 unless exists $options{weaken};
440 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
441 return $class->create($package_name, %options);
445 # this will only get called for
446 # anon-classes, all other calls
447 # are assumed to occur during
448 # global destruction and so don't
449 # really need to be handled explicitly
453 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
455 no warnings 'uninitialized';
456 my $name = $self->name;
457 return unless $name =~ /^$ANON_CLASS_PREFIX/o;
459 # Moose does a weird thing where it replaces the metaclass for
460 # class when fixing metaclass incompatibility. In that case,
461 # we don't want to clean out the namespace now. We can detect
462 # that because Moose will explicitly update the singleton
463 # cache in Class::MOP.
464 my $current_meta = Class::MOP::get_metaclass_by_name($name);
465 return if $current_meta ne $self;
467 my ($serial_id) = ($name =~ /^$ANON_CLASS_PREFIX(\d+)/o);
469 @{$name . '::ISA'} = ();
470 %{$name . '::'} = ();
471 delete ${$ANON_CLASS_PREFIX}{$serial_id . '::'};
473 Class::MOP::remove_metaclass_by_name($name);
478 # creating classes with MOP ...
481 my ( $class, @args ) = @_;
483 unshift @args, 'package' if @args % 2 == 1;
485 my (%options) = @args;
486 my $package_name = $options{package};
488 (ref $options{superclasses} eq 'ARRAY')
489 || confess "You must pass an ARRAY ref of superclasses"
490 if exists $options{superclasses};
492 (ref $options{attributes} eq 'ARRAY')
493 || confess "You must pass an ARRAY ref of attributes"
494 if exists $options{attributes};
496 (ref $options{methods} eq 'HASH')
497 || confess "You must pass a HASH ref of methods"
498 if exists $options{methods};
500 $options{meta_name} = 'meta'
501 unless exists $options{meta_name};
503 my (%initialize_options) = @args;
504 delete @initialize_options{qw(
513 my $meta = $class->initialize( $package_name => %initialize_options );
515 $meta->_instantiate_module( $options{version}, $options{authority} );
517 $meta->_add_meta_method($options{meta_name})
518 if defined $options{meta_name};
520 $meta->superclasses(@{$options{superclasses}})
521 if exists $options{superclasses};
523 # process attributes first, so that they can
524 # install accessors, but locally defined methods
525 # can then overwrite them. It is maybe a little odd, but
526 # I think this should be the order of things.
527 if (exists $options{attributes}) {
528 foreach my $attr (@{$options{attributes}}) {
529 $meta->add_attribute($attr);
532 if (exists $options{methods}) {
533 foreach my $method_name (keys %{$options{methods}}) {
534 $meta->add_method($method_name, $options{methods}->{$method_name});
540 # Instance Construction & Cloning
546 # we need to protect the integrity of the
547 # Class::MOP::Class singletons here, so we
548 # delegate this to &construct_class_instance
549 # which will deal with the singletons
550 return $class->_construct_class_instance(@_)
551 if $class->name->isa('Class::MOP::Class');
552 return $class->_construct_instance(@_);
555 sub _construct_instance {
557 my $params = @_ == 1 ? $_[0] : {@_};
558 my $meta_instance = $class->get_meta_instance();
560 # the code below is almost certainly incorrect
561 # but this is foreign inheritance, so we might
562 # have to kludge it in the end.
564 if (my $instance_class = blessed($params->{__INSTANCE__})) {
565 ($instance_class eq $class->name)
566 || confess "Objects passed as the __INSTANCE__ parameter must "
567 . "already be blessed into the correct class, but "
568 . "$params->{__INSTANCE__} is not a " . $class->name;
569 $instance = $params->{__INSTANCE__};
571 elsif (exists $params->{__INSTANCE__}) {
572 confess "The __INSTANCE__ parameter must be a blessed reference, not "
573 . $params->{__INSTANCE__};
576 $instance = $meta_instance->create_instance();
578 foreach my $attr ($class->get_all_attributes()) {
579 $attr->initialize_instance_slot($meta_instance, $instance, $params);
581 if (Class::MOP::metaclass_is_weak($class->name)) {
582 $meta_instance->_set_mop_slot($instance, $class);
587 sub _inline_new_object {
591 'my $class = shift;',
592 '$class = Scalar::Util::blessed($class) || $class;',
593 $self->_inline_fallback_constructor('$class'),
594 $self->_inline_params('$params', '$class'),
595 $self->_inline_generate_instance('$instance', '$class'),
596 $self->_inline_slot_initializers,
597 $self->_inline_preserve_weak_metaclasses,
598 $self->_inline_extra_init,
603 sub _inline_fallback_constructor {
607 'return ' . $self->_generate_fallback_constructor($class),
608 'if ' . $class . ' ne \'' . $self->name . '\';',
612 sub _generate_fallback_constructor {
615 return 'Class::MOP::Class->initialize(' . $class . ')->new_object(@_)',
620 my ($params, $class) = @_;
622 'my ' . $params . ' = @_ == 1 ? $_[0] : {@_};',
626 sub _inline_generate_instance {
628 my ($inst, $class) = @_;
630 'my ' . $inst . ' = ' . $self->_inline_create_instance($class) . ';',
634 sub _inline_create_instance {
637 return $self->get_meta_instance->inline_create_instance(@_);
640 sub _inline_slot_initializers {
645 return map { $self->_inline_slot_initializer($_, $idx++) }
646 sort { $a->name cmp $b->name } $self->get_all_attributes;
649 sub _inline_slot_initializer {
651 my ($attr, $idx) = @_;
653 my $default = $self->_inline_default_value($attr, $idx);
655 if (defined(my $init_arg = $attr->init_arg)) {
657 'if (exists $params->{\'' . $init_arg . '\'}) {',
658 $attr->_inline_set_value(
659 '$instance', '$params->{\'' . $init_arg . '\'}'
663 if (defined $default) {
666 $attr->_inline_set_value('$instance', $default),
672 elsif (defined $default) {
673 return $attr->_inline_set_value('$instance', $default);
680 sub _inline_default_value {
682 my ($attr, $index) = @_;
684 if ($attr->has_default) {
686 # default values can either be CODE refs
687 # in which case we need to call them. Or
688 # they can be scalars (strings/numbers)
689 # in which case we can just deal with them
690 # in the code we eval.
691 if ($attr->is_default_a_coderef) {
692 return '$defaults->[' . $index . ']->($instance)';
695 return '$defaults->[' . $index . ']';
698 elsif ($attr->has_builder) {
699 return '$instance->' . $attr->builder;
706 sub _inline_preserve_weak_metaclasses {
708 if (Class::MOP::metaclass_is_weak($self->name)) {
710 $self->_inline_set_mop_slot(
711 '$instance', 'Class::MOP::class_of($class)'
720 sub _inline_extra_init { }
723 sub get_meta_instance {
725 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
728 sub _create_meta_instance {
731 my $instance = $self->instance_metaclass->new(
732 associated_metaclass => $self,
733 attributes => [ $self->get_all_attributes() ],
736 $self->add_meta_instance_dependencies()
737 if $instance->is_dependent_on_superclasses();
742 sub _inline_rebless_instance {
745 return $self->get_meta_instance->inline_rebless_instance_structure(@_);
748 sub _inline_get_mop_slot {
751 return $self->get_meta_instance->_inline_get_mop_slot(@_);
754 sub _inline_set_mop_slot {
757 return $self->get_meta_instance->_inline_set_mop_slot(@_);
760 sub _inline_clear_mop_slot {
763 return $self->get_meta_instance->_inline_clear_mop_slot(@_);
768 my $instance = shift;
769 (blessed($instance) && $instance->isa($class->name))
770 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
773 # we need to protect the integrity of the
774 # Class::MOP::Class singletons here, they
775 # should not be cloned.
776 return $instance if $instance->isa('Class::MOP::Class');
777 $class->_clone_instance($instance, @_);
780 sub _clone_instance {
781 my ($class, $instance, %params) = @_;
783 || confess "You can only clone instances, ($instance) is not a blessed instance";
784 my $meta_instance = $class->get_meta_instance();
785 my $clone = $meta_instance->clone_instance($instance);
786 foreach my $attr ($class->get_all_attributes()) {
787 if ( defined( my $init_arg = $attr->init_arg ) ) {
788 if (exists $params{$init_arg}) {
789 $attr->set_value($clone, $params{$init_arg});
796 sub _force_rebless_instance {
797 my ($self, $instance, %params) = @_;
798 my $old_metaclass = Class::MOP::class_of($instance);
800 $old_metaclass->rebless_instance_away($instance, $self, %params)
803 my $meta_instance = $self->get_meta_instance;
805 if (Class::MOP::metaclass_is_weak($old_metaclass->name)) {
806 $meta_instance->_clear_mop_slot($instance);
810 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
811 $meta_instance->rebless_instance_structure($_[1], $self);
813 $self->_fixup_attributes_after_rebless($instance, $old_metaclass, %params);
815 if (Class::MOP::metaclass_is_weak($self->name)) {
816 $meta_instance->_set_mop_slot($instance, $self);
820 sub rebless_instance {
821 my ($self, $instance, %params) = @_;
822 my $old_metaclass = Class::MOP::class_of($instance);
824 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
825 $self->name->isa($old_class)
826 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
828 $self->_force_rebless_instance($_[1], %params);
833 sub rebless_instance_back {
834 my ( $self, $instance ) = @_;
835 my $old_metaclass = Class::MOP::class_of($instance);
838 = $old_metaclass ? $old_metaclass->name : blessed($instance);
839 $old_class->isa( $self->name )
841 "You may rebless only into a superclass of ($old_class), of which ("
845 $self->_force_rebless_instance($_[1]);
850 sub rebless_instance_away {
851 # this intentionally does nothing, it is just a hook
854 sub _fixup_attributes_after_rebless {
856 my ($instance, $rebless_from, %params) = @_;
857 my $meta_instance = $self->get_meta_instance;
859 for my $attr ( $rebless_from->get_all_attributes ) {
860 next if $self->find_attribute_by_name( $attr->name );
861 $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
864 foreach my $attr ( $self->get_all_attributes ) {
865 if ( $attr->has_value($instance) ) {
866 if ( defined( my $init_arg = $attr->init_arg ) ) {
867 $params{$init_arg} = $attr->get_value($instance)
868 unless exists $params{$init_arg};
871 $attr->set_value($instance, $attr->get_value($instance));
876 foreach my $attr ($self->get_all_attributes) {
877 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
881 sub _attach_attribute {
882 my ($self, $attribute) = @_;
883 $attribute->attach_to_class($self);
886 sub _post_add_attribute {
887 my ( $self, $attribute ) = @_;
889 $self->invalidate_meta_instances;
891 # invalidate package flag here
894 $attribute->install_accessors;
897 $self->remove_attribute( $attribute->name );
902 sub remove_attribute {
905 my $removed_attribute = $self->SUPER::remove_attribute(@_)
908 $self->invalidate_meta_instances;
910 $removed_attribute->remove_accessors;
911 $removed_attribute->detach_from_class;
913 return$removed_attribute;
916 sub find_attribute_by_name {
917 my ( $self, $attr_name ) = @_;
919 foreach my $class ( $self->linearized_isa ) {
920 # fetch the meta-class ...
921 my $meta = Class::MOP::Class->initialize($class);
922 return $meta->get_attribute($attr_name)
923 if $meta->has_attribute($attr_name);
929 sub get_all_attributes {
931 my %attrs = map { %{ Class::MOP::Class->initialize($_)->_attribute_map } }
932 reverse $self->linearized_isa;
933 return values %attrs;
941 my $isa = $self->get_or_add_package_symbol('@ISA');
948 # on 5.8 and below, we need to call
949 # a method to get Perl to detect
950 # a cycle in the class hierarchy
951 my $class = $self->name;
955 # we need to check the metaclass
956 # compatibility here so that we can
957 # be sure that the superclass is
958 # not potentially creating an issues
959 # we don't know about
961 $self->_check_metaclass_compatibility();
962 $self->_superclasses_updated();
968 sub _superclasses_updated {
970 $self->update_meta_instance_dependencies();
971 # keep strong references to all our parents, so they don't disappear if
972 # they are anon classes and don't have any direct instances
973 $self->_superclass_metas(
974 map { Class::MOP::class_of($_) } $self->superclasses
978 sub _superclass_metas {
980 $self->{_superclass_metas} = [@_];
985 my $super_class = $self->name;
987 return @{ $super_class->mro::get_isarev() };
990 sub direct_subclasses {
992 my $super_class = $self->name;
997 } Class::MOP::Class->initialize($_)->superclasses
1001 sub linearized_isa {
1002 return @{ mro::get_linear_isa( (shift)->name ) };
1005 sub class_precedence_list {
1007 my $name = $self->name;
1009 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
1011 # We need to check for circular inheritance here
1012 # if we are are not on 5.10, cause 5.8 detects it
1013 # late. This will do nothing if all is well, and
1014 # blow up otherwise. Yes, it's an ugly hack, better
1015 # suggestions are welcome.
1017 ($name || return)->isa('This is a test for circular inheritance')
1020 # if our mro is c3, we can
1021 # just grab the linear_isa
1022 if (mro::get_mro($name) eq 'c3') {
1023 return @{ mro::get_linear_isa($name) }
1027 # we can't grab the linear_isa for dfs
1028 # since it has all the duplicates
1033 Class::MOP::Class->initialize($_)->class_precedence_list()
1034 } $self->superclasses()
1042 my $fetch_and_prepare_method = sub {
1043 my ($self, $method_name) = @_;
1044 my $wrapped_metaclass = $self->wrapped_method_metaclass;
1046 my $method = $self->get_method($method_name);
1047 # if we dont have local ...
1049 # try to find the next method
1050 $method = $self->find_next_method_by_name($method_name);
1051 # die if it does not exist
1053 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
1054 # and now make sure to wrap it
1055 # even if it is already wrapped
1056 # because we need a new sub ref
1057 $method = $wrapped_metaclass->wrap($method,
1058 package_name => $self->name,
1059 name => $method_name,
1063 # now make sure we wrap it properly
1064 $method = $wrapped_metaclass->wrap($method,
1065 package_name => $self->name,
1066 name => $method_name,
1067 ) unless $method->isa($wrapped_metaclass);
1069 $self->add_method($method_name => $method);
1073 sub add_before_method_modifier {
1074 my ($self, $method_name, $method_modifier) = @_;
1075 (defined $method_name && length $method_name)
1076 || confess "You must pass in a method name";
1077 my $method = $fetch_and_prepare_method->($self, $method_name);
1078 $method->add_before_modifier(
1079 subname(':before' => $method_modifier)
1083 sub add_after_method_modifier {
1084 my ($self, $method_name, $method_modifier) = @_;
1085 (defined $method_name && length $method_name)
1086 || confess "You must pass in a method name";
1087 my $method = $fetch_and_prepare_method->($self, $method_name);
1088 $method->add_after_modifier(
1089 subname(':after' => $method_modifier)
1093 sub add_around_method_modifier {
1094 my ($self, $method_name, $method_modifier) = @_;
1095 (defined $method_name && length $method_name)
1096 || confess "You must pass in a method name";
1097 my $method = $fetch_and_prepare_method->($self, $method_name);
1098 $method->add_around_modifier(
1099 subname(':around' => $method_modifier)
1104 # the methods above used to be named like this:
1105 # ${pkg}::${method}:(before|after|around)
1106 # but this proved problematic when using one modifier
1107 # to wrap multiple methods (something which is likely
1108 # to happen pretty regularly IMO). So instead of naming
1109 # it like this, I have chosen to just name them purely
1110 # with their modifier names, like so:
1111 # :(before|after|around)
1112 # The fact is that in a stack trace, it will be fairly
1113 # evident from the context what method they are attached
1114 # to, and so don't need the fully qualified name.
1117 sub find_method_by_name {
1118 my ($self, $method_name) = @_;
1119 (defined $method_name && length $method_name)
1120 || confess "You must define a method name to find";
1121 foreach my $class ($self->linearized_isa) {
1122 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1123 return $method if defined $method;
1128 sub get_all_methods {
1132 for my $class ( reverse $self->linearized_isa ) {
1133 my $meta = Class::MOP::Class->initialize($class);
1135 $methods{ $_->name } = $_ for $meta->_get_local_methods;
1138 return values %methods;
1141 sub get_all_method_names {
1144 return grep { !$uniq{$_}++ } map { Class::MOP::Class->initialize($_)->get_method_list } $self->linearized_isa;
1147 sub find_all_methods_by_name {
1148 my ($self, $method_name) = @_;
1149 (defined $method_name && length $method_name)
1150 || confess "You must define a method name to find";
1152 foreach my $class ($self->linearized_isa) {
1153 # fetch the meta-class ...
1154 my $meta = Class::MOP::Class->initialize($class);
1156 name => $method_name,
1158 code => $meta->get_method($method_name)
1159 } if $meta->has_method($method_name);
1164 sub find_next_method_by_name {
1165 my ($self, $method_name) = @_;
1166 (defined $method_name && length $method_name)
1167 || confess "You must define a method name to find";
1168 my @cpl = $self->linearized_isa;
1169 shift @cpl; # discard ourselves
1170 foreach my $class (@cpl) {
1171 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1172 return $method if defined $method;
1177 sub update_meta_instance_dependencies {
1180 if ( $self->{meta_instance_dependencies} ) {
1181 return $self->add_meta_instance_dependencies;
1185 sub add_meta_instance_dependencies {
1188 $self->remove_meta_instance_dependencies;
1190 my @attrs = $self->get_all_attributes();
1193 my @classes = grep { not $seen{ $_->name }++ }
1194 map { $_->associated_class } @attrs;
1196 foreach my $class (@classes) {
1197 $class->add_dependent_meta_instance($self);
1200 $self->{meta_instance_dependencies} = \@classes;
1203 sub remove_meta_instance_dependencies {
1206 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
1207 foreach my $class (@$classes) {
1208 $class->remove_dependent_meta_instance($self);
1218 sub add_dependent_meta_instance {
1219 my ( $self, $metaclass ) = @_;
1220 push @{ $self->{dependent_meta_instances} }, $metaclass;
1223 sub remove_dependent_meta_instance {
1224 my ( $self, $metaclass ) = @_;
1225 my $name = $metaclass->name;
1226 @$_ = grep { $_->name ne $name } @$_
1227 for $self->{dependent_meta_instances};
1230 sub invalidate_meta_instances {
1232 $_->invalidate_meta_instance()
1233 for $self, @{ $self->{dependent_meta_instances} };
1236 sub invalidate_meta_instance {
1238 undef $self->{_meta_instance};
1241 # check if we can reinitialize
1245 # if any local attr is defined
1246 return if $self->get_attribute_list;
1248 # or any non-declared methods
1249 for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1250 return if $method->isa("Class::MOP::Method::Generated");
1251 # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1259 sub is_mutable { 1 }
1260 sub is_immutable { 0 }
1262 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1264 sub _immutable_options {
1265 my ( $self, @args ) = @_;
1268 inline_accessors => 1,
1269 inline_constructor => 1,
1270 inline_destructor => 0,
1272 immutable_trait => $self->immutable_trait,
1273 constructor_name => $self->constructor_name,
1274 constructor_class => $self->constructor_class,
1275 destructor_class => $self->destructor_class,
1280 sub make_immutable {
1281 my ( $self, @args ) = @_;
1283 if ( $self->is_mutable ) {
1284 $self->_initialize_immutable( $self->_immutable_options(@args) );
1285 $self->_rebless_as_immutable(@args);
1296 if ( $self->is_immutable ) {
1297 my @args = $self->immutable_options;
1298 $self->_rebless_as_mutable();
1299 $self->_remove_inlined_code(@args);
1300 delete $self->{__immutable};
1308 sub _rebless_as_immutable {
1309 my ( $self, @args ) = @_;
1311 $self->{__immutable}{original_class} = ref $self;
1313 bless $self => $self->_immutable_metaclass(@args);
1316 sub _immutable_metaclass {
1317 my ( $self, %args ) = @_;
1319 if ( my $class = $args{immutable_metaclass} ) {
1323 my $trait = $args{immutable_trait} = $self->immutable_trait
1324 || confess "no immutable trait specified for $self";
1326 my $meta = $self->meta;
1327 my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1331 if ( $meta_attr and $trait eq $meta_attr->default ) {
1332 # if the trait is the same as the default we try and pick a
1333 # predictable name for the immutable metaclass
1334 $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1337 $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1338 $trait, 'ForMetaClass', ref($self);
1342 if Class::MOP::is_class_loaded($class_name);
1344 # If the metaclass is a subclass of CMOP::Class which has had
1345 # metaclass roles applied (via Moose), then we want to make sure
1346 # that we preserve that anonymous class (see Fey::ORM for an
1347 # example of where this matters).
1348 my $meta_name = $meta->_real_ref_name;
1350 my $immutable_meta = $meta_name->create(
1352 superclasses => [ ref $self ],
1355 Class::MOP::MiniTrait::apply( $immutable_meta, $trait );
1357 $immutable_meta->make_immutable(
1358 inline_constructor => 0,
1359 inline_accessors => 0,
1365 sub _remove_inlined_code {
1368 $self->remove_method( $_->name ) for $self->_inlined_methods;
1370 delete $self->{__immutable}{inlined_methods};
1373 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1375 sub _add_inlined_method {
1376 my ( $self, $method ) = @_;
1378 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1381 sub _initialize_immutable {
1382 my ( $self, %args ) = @_;
1384 $self->{__immutable}{options} = \%args;
1385 $self->_install_inlined_code(%args);
1388 sub _install_inlined_code {
1389 my ( $self, %args ) = @_;
1392 $self->_inline_accessors(%args) if $args{inline_accessors};
1393 $self->_inline_constructor(%args) if $args{inline_constructor};
1394 $self->_inline_destructor(%args) if $args{inline_destructor};
1397 sub _rebless_as_mutable {
1400 bless $self, $self->_get_mutable_metaclass_name;
1405 sub _inline_accessors {
1408 foreach my $attr_name ( $self->get_attribute_list ) {
1409 $self->get_attribute($attr_name)->install_accessors(1);
1413 sub _inline_constructor {
1414 my ( $self, %args ) = @_;
1416 my $name = $args{constructor_name};
1417 # A class may not even have a constructor, and that's okay.
1418 return unless defined $name;
1420 if ( $self->has_method($name) && !$args{replace_constructor} ) {
1421 my $class = $self->name;
1422 warn "Not inlining a constructor for $class since it defines"
1423 . " its own constructor.\n"
1424 . "If you are certain you don't need to inline your"
1425 . " constructor, specify inline_constructor => 0 in your"
1426 . " call to $class->meta->make_immutable\n";
1430 my $constructor_class = $args{constructor_class};
1432 Class::MOP::load_class($constructor_class);
1434 my $constructor = $constructor_class->new(
1438 package_name => $self->name,
1442 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1443 $self->add_method( $name => $constructor );
1444 $self->_add_inlined_method($constructor);
1448 sub _inline_destructor {
1449 my ( $self, %args ) = @_;
1451 ( exists $args{destructor_class} && defined $args{destructor_class} )
1452 || confess "The 'inline_destructor' option is present, but "
1453 . "no destructor class was specified";
1455 if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1456 my $class = $self->name;
1457 warn "Not inlining a destructor for $class since it defines"
1458 . " its own destructor.\n";
1462 my $destructor_class = $args{destructor_class};
1464 Class::MOP::load_class($destructor_class);
1466 return unless $destructor_class->is_needed($self);
1468 my $destructor = $destructor_class->new(
1471 package_name => $self->name,
1475 if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1476 $self->add_method( 'DESTROY' => $destructor );
1477 $self->_add_inlined_method($destructor);
1489 Class::MOP::Class - Class Meta Object
1493 # assuming that class Foo
1494 # has been defined, you can
1496 # use this for introspection ...
1498 # add a method to Foo ...
1499 Foo->meta->add_method( 'bar' => sub {...} )
1501 # get a list of all the classes searched
1502 # the method dispatcher in the correct order
1503 Foo->meta->class_precedence_list()
1505 # remove a method from Foo
1506 Foo->meta->remove_method('bar');
1508 # or use this to actually create classes ...
1510 Class::MOP::Class->create(
1513 superclasses => ['Foo'],
1515 Class::MOP::Attribute->new('$bar'),
1516 Class::MOP::Attribute->new('$baz'),
1519 calculate_bar => sub {...},
1520 construct_baz => sub {...}
1527 The Class Protocol is the largest and most complex part of the
1528 Class::MOP meta-object protocol. It controls the introspection and
1529 manipulation of Perl 5 classes, and it can create them as well. The
1530 best way to understand what this module can do is to read the
1531 documentation for each of its methods.
1535 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1539 =head2 Class construction
1541 These methods all create new C<Class::MOP::Class> objects. These
1542 objects can represent existing classes or they can be used to create
1543 new classes from scratch.
1545 The metaclass object for a given class is a singleton. If you attempt
1546 to create a metaclass for the same class twice, you will just get the
1551 =item B<< Class::MOP::Class->create($package_name, %options) >>
1553 This method creates a new C<Class::MOP::Class> object with the given
1554 package name. It accepts a number of options:
1560 An optional version number for the newly created package.
1564 An optional authority for the newly created package.
1566 =item * superclasses
1568 An optional array reference of superclass names.
1572 An optional hash reference of methods for the class. The keys of the
1573 hash reference are method names and values are subroutine references.
1577 An optional array reference of L<Class::MOP::Attribute> objects.
1581 Specifies the name to install the C<meta> method for this class under.
1582 If it is not passed, C<meta> is assumed, and if C<undef> is explicitly
1583 given, no meta method will be installed.
1587 If true, the metaclass that is stored in the global cache will be a
1590 Classes created in this way are destroyed once the metaclass they are
1591 attached to goes out of scope, and will be removed from Perl's internal
1594 All instances of a class with a weakened metaclass keep a special
1595 reference to the metaclass object, which prevents the metaclass from
1596 going out of scope while any instances exist.
1598 This only works if the instance is based on a hash reference, however.
1602 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1604 This method works just like C<< Class::MOP::Class->create >> but it
1605 creates an "anonymous" class. In fact, the class does have a name, but
1606 that name is a unique name generated internally by this module.
1608 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1609 parameters that C<create> accepts.
1611 Anonymous classes default to C<< weaken => 1 >>, although this can be
1614 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1616 This method will initialize a C<Class::MOP::Class> object for the
1617 named package. Unlike C<create>, this method I<will not> create a new
1620 The purpose of this method is to retrieve a C<Class::MOP::Class>
1621 object for introspecting an existing class.
1623 If an existing C<Class::MOP::Class> object exists for the named
1624 package, it will be returned, and any options provided will be
1627 If the object does not yet exist, it will be created.
1629 The valid options that can be passed to this method are
1630 C<attribute_metaclass>, C<method_metaclass>,
1631 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1632 optional, and default to the appropriate class in the C<Class::MOP>
1637 =head2 Object instance construction and cloning
1639 These methods are all related to creating and/or cloning object
1644 =item B<< $metaclass->clone_object($instance, %params) >>
1646 This method clones an existing object instance. Any parameters you
1647 provide are will override existing attribute values in the object.
1649 This is a convenience method for cloning an object instance, then
1650 blessing it into the appropriate package.
1652 You could implement a clone method in your class, using this method:
1655 my ($self, %params) = @_;
1656 $self->meta->clone_object($self, %params);
1659 =item B<< $metaclass->rebless_instance($instance, %params) >>
1661 This method changes the class of C<$instance> to the metaclass's class.
1663 You can only rebless an instance into a subclass of its current
1664 class. If you pass any additional parameters, these will be treated
1665 like constructor parameters and used to initialize the object's
1666 attributes. Any existing attributes that are already set will be
1669 Before reblessing the instance, this method will call
1670 C<rebless_instance_away> on the instance's current metaclass. This method
1671 will be passed the instance, the new metaclass, and any parameters
1672 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1673 does nothing; it is merely a hook.
1675 =item B<< $metaclass->rebless_instance_back($instance) >>
1677 Does the same thing as C<rebless_instance>, except that you can only
1678 rebless an instance into one of its superclasses. Any attributes that
1679 do not exist in the superclass will be deinitialized.
1681 This is a much more dangerous operation than C<rebless_instance>,
1682 especially when multiple inheritance is involved, so use this carefully!
1684 =item B<< $metaclass->new_object(%params) >>
1686 This method is used to create a new object of the metaclass's
1687 class. Any parameters you provide are used to initialize the
1688 instance's attributes. A special C<__INSTANCE__> key can be passed to
1689 provide an already generated instance, rather than having Class::MOP
1690 generate it for you. This is mostly useful for using Class::MOP with
1691 foreign classes which generate instances using their own constructors.
1693 =item B<< $metaclass->instance_metaclass >>
1695 Returns the class name of the instance metaclass. See
1696 L<Class::MOP::Instance> for more information on the instance
1699 =item B<< $metaclass->get_meta_instance >>
1701 Returns an instance of the C<instance_metaclass> to be used in the
1702 construction of a new instance of the class.
1706 =head2 Informational predicates
1708 These are a few predicate methods for asking information about the
1713 =item B<< $metaclass->is_anon_class >>
1715 This returns true if the class was created by calling C<<
1716 Class::MOP::Class->create_anon_class >>.
1718 =item B<< $metaclass->is_mutable >>
1720 This returns true if the class is still mutable.
1722 =item B<< $metaclass->is_immutable >>
1724 This returns true if the class has been made immutable.
1726 =item B<< $metaclass->is_pristine >>
1728 A class is I<not> pristine if it has non-inherited attributes or if it
1729 has any generated methods.
1733 =head2 Inheritance Relationships
1737 =item B<< $metaclass->superclasses(@superclasses) >>
1739 This is a read-write accessor which represents the superclass
1740 relationships of the metaclass's class.
1742 This is basically sugar around getting and setting C<@ISA>.
1744 =item B<< $metaclass->class_precedence_list >>
1746 This returns a list of all of the class's ancestor classes. The
1747 classes are returned in method dispatch order.
1749 =item B<< $metaclass->linearized_isa >>
1751 This returns a list based on C<class_precedence_list> but with all
1754 =item B<< $metaclass->subclasses >>
1756 This returns a list of all subclasses for this class, even indirect
1759 =item B<< $metaclass->direct_subclasses >>
1761 This returns a list of immediate subclasses for this class, which does not
1762 include indirect subclasses.
1766 =head2 Method introspection and creation
1768 These methods allow you to introspect a class's methods, as well as
1769 add, remove, or change methods.
1771 Determining what is truly a method in a Perl 5 class requires some
1772 heuristics (aka guessing).
1774 Methods defined outside the package with a fully qualified name (C<sub
1775 Package::name { ... }>) will be included. Similarly, methods named
1776 with a fully qualified name using L<Sub::Name> are also included.
1778 However, we attempt to ignore imported functions.
1780 Ultimately, we are using heuristics to determine what truly is a
1781 method in a class, and these heuristics may get the wrong answer in
1782 some edge cases. However, for most "normal" cases the heuristics work
1787 =item B<< $metaclass->get_method($method_name) >>
1789 This will return a L<Class::MOP::Method> for the specified
1790 C<$method_name>. If the class does not have the specified method, it
1793 =item B<< $metaclass->has_method($method_name) >>
1795 Returns a boolean indicating whether or not the class defines the
1796 named method. It does not include methods inherited from parent
1799 =item B<< $metaclass->get_method_list >>
1801 This will return a list of method I<names> for all methods defined in
1804 =item B<< $metaclass->add_method($method_name, $method) >>
1806 This method takes a method name and a subroutine reference, and adds
1807 the method to the class.
1809 The subroutine reference can be a L<Class::MOP::Method>, and you are
1810 strongly encouraged to pass a meta method object instead of a code
1811 reference. If you do so, that object gets stored as part of the
1812 class's method map directly. If not, the meta information will have to
1813 be recreated later, and may be incorrect.
1815 If you provide a method object, this method will clone that object if
1816 the object's package name does not match the class name. This lets us
1817 track the original source of any methods added from other classes
1818 (notably Moose roles).
1820 =item B<< $metaclass->remove_method($method_name) >>
1822 Remove the named method from the class. This method returns the
1823 L<Class::MOP::Method> object for the method.
1825 =item B<< $metaclass->method_metaclass >>
1827 Returns the class name of the method metaclass, see
1828 L<Class::MOP::Method> for more information on the method metaclass.
1830 =item B<< $metaclass->wrapped_method_metaclass >>
1832 Returns the class name of the wrapped method metaclass, see
1833 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1836 =item B<< $metaclass->get_all_methods >>
1838 This will traverse the inheritance hierarchy and return a list of all
1839 the L<Class::MOP::Method> objects for this class and its parents.
1841 =item B<< $metaclass->find_method_by_name($method_name) >>
1843 This will return a L<Class::MOP::Method> for the specified
1844 C<$method_name>. If the class does not have the specified method, it
1847 Unlike C<get_method>, this method I<will> look for the named method in
1850 =item B<< $metaclass->get_all_method_names >>
1852 This will return a list of method I<names> for all of this class's
1853 methods, including inherited methods.
1855 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1857 This method looks for the named method in the class and all of its
1858 parents. It returns every matching method it finds in the inheritance
1859 tree, so it returns a list of methods.
1861 Each method is returned as a hash reference with three keys. The keys
1862 are C<name>, C<class>, and C<code>. The C<code> key has a
1863 L<Class::MOP::Method> object as its value.
1865 The list of methods is distinct.
1867 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1869 This method returns the first method in any superclass matching the
1870 given name. It is effectively the method that C<SUPER::$method_name>
1875 =head2 Attribute introspection and creation
1877 Because Perl 5 does not have a core concept of attributes in classes,
1878 we can only return information about attributes which have been added
1879 via this class's methods. We cannot discover information about
1880 attributes which are defined in terms of "regular" Perl 5 methods.
1884 =item B<< $metaclass->get_attribute($attribute_name) >>
1886 This will return a L<Class::MOP::Attribute> for the specified
1887 C<$attribute_name>. If the class does not have the specified
1888 attribute, it returns C<undef>.
1890 NOTE that get_attribute does not search superclasses, for that you
1891 need to use C<find_attribute_by_name>.
1893 =item B<< $metaclass->has_attribute($attribute_name) >>
1895 Returns a boolean indicating whether or not the class defines the
1896 named attribute. It does not include attributes inherited from parent
1899 =item B<< $metaclass->get_attribute_list >>
1901 This will return a list of attributes I<names> for all attributes
1902 defined in this class. Note that this operates on the current class
1903 only, it does not traverse the inheritance hierarchy.
1905 =item B<< $metaclass->get_all_attributes >>
1907 This will traverse the inheritance hierarchy and return a list of all
1908 the L<Class::MOP::Attribute> objects for this class and its parents.
1910 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1912 This will return a L<Class::MOP::Attribute> for the specified
1913 C<$attribute_name>. If the class does not have the specified
1914 attribute, it returns C<undef>.
1916 Unlike C<get_attribute>, this attribute I<will> look for the named
1917 attribute in superclasses.
1919 =item B<< $metaclass->add_attribute(...) >>
1921 This method accepts either an existing L<Class::MOP::Attribute>
1922 object or parameters suitable for passing to that class's C<new>
1925 The attribute provided will be added to the class.
1927 Any accessor methods defined by the attribute will be added to the
1928 class when the attribute is added.
1930 If an attribute of the same name already exists, the old attribute
1931 will be removed first.
1933 =item B<< $metaclass->remove_attribute($attribute_name) >>
1935 This will remove the named attribute from the class, and
1936 L<Class::MOP::Attribute> object.
1938 Removing an attribute also removes any accessor methods defined by the
1941 However, note that removing an attribute will only affect I<future>
1942 object instances created for this class, not existing instances.
1944 =item B<< $metaclass->attribute_metaclass >>
1946 Returns the class name of the attribute metaclass for this class. By
1947 default, this is L<Class::MOP::Attribute>.
1951 =head2 Class Immutability
1953 Making a class immutable "freezes" the class definition. You can no
1954 longer call methods which alter the class, such as adding or removing
1955 methods or attributes.
1957 Making a class immutable lets us optimize the class by inlining some
1958 methods, and also allows us to optimize some methods on the metaclass
1961 After immutabilization, the metaclass object will cache most informational
1962 methods that returns information about methods or attributes. Methods which
1963 would alter the class, such as C<add_attribute> and C<add_method>, will
1964 throw an error on an immutable metaclass object.
1966 The immutabilization system in L<Moose> takes much greater advantage
1967 of the inlining features than Class::MOP itself does.
1971 =item B<< $metaclass->make_immutable(%options) >>
1973 This method will create an immutable transformer and use it to make
1974 the class and its metaclass object immutable.
1976 This method accepts the following options:
1980 =item * inline_accessors
1982 =item * inline_constructor
1984 =item * inline_destructor
1986 These are all booleans indicating whether the specified method(s)
1989 By default, accessors and the constructor are inlined, but not the
1992 =item * immutable_trait
1994 The name of a class which will be used as a parent class for the
1995 metaclass object being made immutable. This "trait" implements the
1996 post-immutability functionality of the metaclass (but not the
1997 transformation itself).
1999 This defaults to L<Class::MOP::Class::Immutable::Trait>.
2001 =item * constructor_name
2003 This is the constructor method name. This defaults to "new".
2005 =item * constructor_class
2007 The name of the method metaclass for constructors. It will be used to
2008 generate the inlined constructor. This defaults to
2009 "Class::MOP::Method::Constructor".
2011 =item * replace_constructor
2013 This is a boolean indicating whether an existing constructor should be
2014 replaced when inlining a constructor. This defaults to false.
2016 =item * destructor_class
2018 The name of the method metaclass for destructors. It will be used to
2019 generate the inlined destructor. This defaults to
2020 "Class::MOP::Method::Denstructor".
2022 =item * replace_destructor
2024 This is a boolean indicating whether an existing destructor should be
2025 replaced when inlining a destructor. This defaults to false.
2029 =item B<< $metaclass->immutable_options >>
2031 Returns a hash of the options used when making the class immutable, including
2032 both defaults and anything supplied by the user in the call to C<<
2033 $metaclass->make_immutable >>. This is useful if you need to temporarily make
2034 a class mutable and then restore immutability as it was before.
2036 =item B<< $metaclass->make_mutable >>
2038 Calling this method reverse the immutabilization transformation.
2042 =head2 Method Modifiers
2044 Method modifiers are hooks which allow a method to be wrapped with
2045 I<before>, I<after> and I<around> method modifiers. Every time a
2046 method is called, its modifiers are also called.
2048 A class can modify its own methods, as well as methods defined in
2051 =head3 How method modifiers work?
2053 Method modifiers work by wrapping the original method and then
2054 replacing it in the class's symbol table. The wrappers will handle
2055 calling all the modifiers in the appropriate order and preserving the
2056 calling context for the original method.
2058 The return values of C<before> and C<after> modifiers are
2059 ignored. This is because their purpose is B<not> to filter the input
2060 and output of the primary method (this is done with an I<around>
2063 This may seem like an odd restriction to some, but doing this allows
2064 for simple code to be added at the beginning or end of a method call
2065 without altering the function of the wrapped method or placing any
2066 extra responsibility on the code of the modifier.
2068 Of course if you have more complex needs, you can use the C<around>
2069 modifier which allows you to change both the parameters passed to the
2070 wrapped method, as well as its return value.
2072 Before and around modifiers are called in last-defined-first-called
2073 order, while after modifiers are called in first-defined-first-called
2074 order. So the call tree might looks something like this:
2086 =head3 What is the performance impact?
2088 Of course there is a performance cost associated with method
2089 modifiers, but we have made every effort to make that cost directly
2090 proportional to the number of modifier features you use.
2092 The wrapping method does its best to B<only> do as much work as it
2093 absolutely needs to. In order to do this we have moved some of the
2094 performance costs to set-up time, where they are easier to amortize.
2096 All this said, our benchmarks have indicated the following:
2098 simple wrapper with no modifiers 100% slower
2099 simple wrapper with simple before modifier 400% slower
2100 simple wrapper with simple after modifier 450% slower
2101 simple wrapper with simple around modifier 500-550% slower
2102 simple wrapper with all 3 modifiers 1100% slower
2104 These numbers may seem daunting, but you must remember, every feature
2105 comes with some cost. To put things in perspective, just doing a
2106 simple C<AUTOLOAD> which does nothing but extract the name of the
2107 method called and return it costs about 400% over a normal method
2112 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
2114 This wraps the specified method with the supplied subroutine
2115 reference. The modifier will be called as a method itself, and will
2116 receive the same arguments as are passed to the method.
2118 When the modifier exits, the wrapped method will be called.
2120 The return value of the modifier will be ignored.
2122 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
2124 This wraps the specified method with the supplied subroutine
2125 reference. The modifier will be called as a method itself, and will
2126 receive the same arguments as are passed to the method.
2128 When the wrapped methods exits, the modifier will be called.
2130 The return value of the modifier will be ignored.
2132 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
2134 This wraps the specified method with the supplied subroutine
2137 The first argument passed to the modifier will be a subroutine
2138 reference to the wrapped method. The second argument is the object,
2139 and after that come any arguments passed when the method is called.
2141 The around modifier can choose to call the original method, as well as
2142 what arguments to pass if it does so.
2144 The return value of the modifier is what will be seen by the caller.
2148 =head2 Introspection
2152 =item B<< Class::MOP::Class->meta >>
2154 This will return a L<Class::MOP::Class> instance for this class.
2156 It should also be noted that L<Class::MOP> will actually bootstrap
2157 this module by installing a number of attribute meta-objects into its
2164 Stevan Little E<lt>stevan@iinteractive.comE<gt>
2166 =head1 COPYRIGHT AND LICENSE
2168 Copyright 2006-2010 by Infinity Interactive, Inc.
2170 L<http://www.iinteractive.com>
2172 This library is free software; you can redistribute it and/or modify
2173 it under the same terms as Perl itself.