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 $AUTHORITY = 'cpan:STEVAN';
22 use base 'Class::MOP::Module',
23 'Class::MOP::Mixin::HasAttributes',
24 'Class::MOP::Mixin::HasMethods';
34 $package_name = shift;
37 $package_name = $options{package};
40 ($package_name && !ref($package_name))
41 || confess "You must pass a package name and it cannot be blessed";
43 return Class::MOP::get_metaclass_by_name($package_name)
44 || $class->_construct_class_instance(package => $package_name, @_);
48 my ( $class, @args ) = @_;
49 unshift @args, "package" if @args % 2;
51 my $old_metaclass = blessed($options{package})
53 : Class::MOP::get_metaclass_by_name($options{package});
54 $options{weaken} = Class::MOP::metaclass_is_weak($old_metaclass->name)
55 if !exists $options{weaken}
56 && blessed($old_metaclass)
57 && $old_metaclass->isa('Class::MOP::Class');
58 $old_metaclass->_remove_generated_metaobjects
59 if $old_metaclass && $old_metaclass->isa('Class::MOP::Class');
60 my $new_metaclass = $class->SUPER::reinitialize(%options);
61 $new_metaclass->_restore_metaobjects_from($old_metaclass)
62 if $old_metaclass && $old_metaclass->isa('Class::MOP::Class');
63 return $new_metaclass;
66 # NOTE: (meta-circularity)
67 # this is a special form of _construct_instance
68 # (see below), which is used to construct class
69 # meta-object instances for any Class::MOP::*
70 # class. All other classes will use the more
71 # normal &construct_instance.
72 sub _construct_class_instance {
74 my $options = @_ == 1 ? $_[0] : {@_};
75 my $package_name = $options->{package};
76 (defined $package_name && $package_name)
77 || confess "You must pass a package name";
79 # return the metaclass if we have it cached,
80 # and it is still defined (it has not been
81 # reaped by DESTROY yet, which can happen
82 # annoyingly enough during global destruction)
84 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
90 ? $class->_real_ref_name
93 # now create the metaclass
95 if ($class eq 'Class::MOP::Class') {
96 $meta = $class->_new($options);
100 # it is safe to use meta here because
101 # class will always be a subclass of
102 # Class::MOP::Class, which defines meta
103 $meta = $class->meta->_construct_instance($options)
106 # and check the metaclass compatibility
107 $meta->_check_metaclass_compatibility();
109 Class::MOP::store_metaclass_by_name($package_name, $meta);
112 # we need to weaken any anon classes
113 # so that they can call DESTROY properly
114 Class::MOP::weaken_metaclass($package_name) if $options->{weaken};
122 # NOTE: we need to deal with the possibility of class immutability here,
123 # and then get the name of the class appropriately
124 return $self->is_immutable
125 ? $self->_get_mutable_metaclass_name()
132 return Class::MOP::Class->initialize($class)->new_object(@_)
133 if $class ne __PACKAGE__;
135 my $options = @_ == 1 ? $_[0] : {@_};
138 # inherited from Class::MOP::Package
139 'package' => $options->{package},
142 # since the following attributes will
143 # actually be loaded from the symbol
144 # table, and actually bypass the instance
145 # entirely, we can just leave these things
146 # listed here for reference, because they
147 # should not actually have a value associated
149 'namespace' => \undef,
152 # inherited from Class::MOP::Module
154 'authority' => \undef,
156 # defined in Class::MOP::Class
157 'superclasses' => \undef,
160 'attribute_metaclass' =>
161 ( $options->{'attribute_metaclass'} || 'Class::MOP::Attribute' ),
162 'method_metaclass' =>
163 ( $options->{'method_metaclass'} || 'Class::MOP::Method' ),
164 'wrapped_method_metaclass' => (
165 $options->{'wrapped_method_metaclass'}
166 || 'Class::MOP::Method::Wrapped'
168 'instance_metaclass' =>
169 ( $options->{'instance_metaclass'} || 'Class::MOP::Instance' ),
170 'immutable_trait' => (
171 $options->{'immutable_trait'}
172 || 'Class::MOP::Class::Immutable::Trait'
174 'constructor_name' => ( $options->{constructor_name} || 'new' ),
175 'constructor_class' => (
176 $options->{constructor_class} || 'Class::MOP::Method::Constructor'
178 'destructor_class' => $options->{destructor_class},
182 ## Metaclass compatibility
184 my %base_metaclass = (
185 attribute_metaclass => 'Class::MOP::Attribute',
186 method_metaclass => 'Class::MOP::Method',
187 wrapped_method_metaclass => 'Class::MOP::Method::Wrapped',
188 instance_metaclass => 'Class::MOP::Instance',
189 constructor_class => 'Class::MOP::Method::Constructor',
190 destructor_class => 'Class::MOP::Method::Destructor',
193 sub _base_metaclasses { %base_metaclass }
196 sub _check_metaclass_compatibility {
199 my @superclasses = $self->superclasses
202 $self->_fix_metaclass_incompatibility(@superclasses);
204 my %base_metaclass = $self->_base_metaclasses;
206 # this is always okay ...
208 if ref($self) eq 'Class::MOP::Class'
210 my $meta = $self->$_;
211 !defined($meta) || $meta eq $base_metaclass{$_};
213 keys %base_metaclass;
215 for my $superclass (@superclasses) {
216 $self->_check_class_metaclass_compatibility($superclass);
219 for my $metaclass_type ( keys %base_metaclass ) {
220 next unless defined $self->$metaclass_type;
221 for my $superclass (@superclasses) {
222 $self->_check_single_metaclass_compatibility( $metaclass_type,
228 sub _check_class_metaclass_compatibility {
230 my ( $superclass_name ) = @_;
232 if (!$self->_class_metaclass_is_compatible($superclass_name)) {
233 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
235 my $super_meta_type = $super_meta->_real_ref_name;
237 confess "The metaclass of " . $self->name . " ("
238 . (ref($self)) . ")" . " is not compatible with "
239 . "the metaclass of its superclass, "
240 . $superclass_name . " (" . ($super_meta_type) . ")";
244 sub _class_metaclass_is_compatible {
246 my ( $superclass_name ) = @_;
248 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
251 my $super_meta_name = $super_meta->_real_ref_name;
253 return $self->_is_compatible_with($super_meta_name);
256 sub _check_single_metaclass_compatibility {
258 my ( $metaclass_type, $superclass_name ) = @_;
260 if (!$self->_single_metaclass_is_compatible($metaclass_type, $superclass_name)) {
261 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
262 my $metaclass_type_name = $metaclass_type;
263 $metaclass_type_name =~ s/_(?:meta)?class$//;
264 $metaclass_type_name =~ s/_/ /g;
265 confess "The $metaclass_type_name metaclass for "
266 . $self->name . " (" . ($self->$metaclass_type)
267 . ")" . " is not compatible with the "
268 . "$metaclass_type_name metaclass of its "
269 . "superclass, $superclass_name ("
270 . ($super_meta->$metaclass_type) . ")";
274 sub _single_metaclass_is_compatible {
276 my ( $metaclass_type, $superclass_name ) = @_;
278 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
281 # for instance, Moose::Meta::Class has a error_class attribute, but
282 # Class::MOP::Class doesn't - this shouldn't be an error
283 return 1 unless $super_meta->can($metaclass_type);
284 # for instance, Moose::Meta::Class has a destructor_class, but
285 # Class::MOP::Class doesn't - this shouldn't be an error
286 return 1 unless defined $super_meta->$metaclass_type;
287 # if metaclass is defined in superclass but not here, it's not compatible
288 # this is a really odd case
289 return 0 unless defined $self->$metaclass_type;
291 return $self->$metaclass_type->_is_compatible_with($super_meta->$metaclass_type);
294 sub _fix_metaclass_incompatibility {
296 my @supers = map { Class::MOP::Class->initialize($_) } @_;
299 for my $super (@supers) {
301 if $self->_can_fix_metaclass_incompatibility($super);
303 return unless $necessary;
305 for my $super (@supers) {
306 if (!$self->_class_metaclass_is_compatible($super->name)) {
307 $self->_fix_class_metaclass_incompatibility($super);
311 my %base_metaclass = $self->_base_metaclasses;
312 for my $metaclass_type (keys %base_metaclass) {
313 for my $super (@supers) {
314 if (!$self->_single_metaclass_is_compatible($metaclass_type, $super->name)) {
315 $self->_fix_single_metaclass_incompatibility(
316 $metaclass_type, $super
323 sub _can_fix_metaclass_incompatibility {
325 my ($super_meta) = @_;
327 return 1 if $self->_class_metaclass_can_be_made_compatible($super_meta);
329 my %base_metaclass = $self->_base_metaclasses;
330 for my $metaclass_type (keys %base_metaclass) {
331 return 1 if $self->_single_metaclass_can_be_made_compatible($super_meta, $metaclass_type);
337 sub _class_metaclass_can_be_made_compatible {
339 my ($super_meta) = @_;
341 return $self->_can_be_made_compatible_with($super_meta->_real_ref_name);
344 sub _single_metaclass_can_be_made_compatible {
346 my ($super_meta, $metaclass_type) = @_;
348 my $specific_meta = $self->$metaclass_type;
350 return unless $super_meta->can($metaclass_type);
351 my $super_specific_meta = $super_meta->$metaclass_type;
353 # for instance, Moose::Meta::Class has a destructor_class, but
354 # Class::MOP::Class doesn't - this shouldn't be an error
355 return unless defined $super_specific_meta;
357 # if metaclass is defined in superclass but not here, it's fixable
358 # this is a really odd case
359 return 1 unless defined $specific_meta;
361 return 1 if $specific_meta->_can_be_made_compatible_with($super_specific_meta);
364 sub _fix_class_metaclass_incompatibility {
366 my ( $super_meta ) = @_;
368 if ($self->_class_metaclass_can_be_made_compatible($super_meta)) {
370 || confess "Can't fix metaclass incompatibility for "
372 . " because it is not pristine.";
374 my $super_meta_name = $super_meta->_real_ref_name;
376 $self->_make_compatible_with($super_meta_name);
380 sub _fix_single_metaclass_incompatibility {
382 my ( $metaclass_type, $super_meta ) = @_;
384 if ($self->_single_metaclass_can_be_made_compatible($super_meta, $metaclass_type)) {
386 || confess "Can't fix metaclass incompatibility for "
388 . " because it is not pristine.";
390 my $new_metaclass = $self->$metaclass_type
391 ? $self->$metaclass_type->_get_compatible_metaclass($super_meta->$metaclass_type)
392 : $super_meta->$metaclass_type;
393 $self->{$metaclass_type} = $new_metaclass;
397 sub _restore_metaobjects_from {
401 $self->_restore_metamethods_from($old_meta);
402 $self->_restore_metaattributes_from($old_meta);
405 sub _remove_generated_metaobjects {
408 for my $attr (map { $self->get_attribute($_) } $self->get_attribute_list) {
409 $attr->remove_accessors;
417 # this should be sufficient, if you have a
418 # use case where it is not, write a test and
420 my $ANON_CLASS_SERIAL = 0;
423 # we need a sufficiently annoying prefix
424 # this should suffice for now, this is
425 # used in a couple of places below, so
426 # need to put it up here for now.
427 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
431 no warnings 'uninitialized';
432 $self->name =~ /^$ANON_CLASS_PREFIX/o;
435 sub create_anon_class {
436 my ($class, %options) = @_;
437 $options{weaken} = 1 unless exists $options{weaken};
438 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
439 return $class->create($package_name, %options);
443 # this will only get called for
444 # anon-classes, all other calls
445 # are assumed to occur during
446 # global destruction and so don't
447 # really need to be handled explicitly
451 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
453 no warnings 'uninitialized';
454 my $name = $self->name;
455 return unless $name =~ /^$ANON_CLASS_PREFIX/o;
457 # Moose does a weird thing where it replaces the metaclass for
458 # class when fixing metaclass incompatibility. In that case,
459 # we don't want to clean out the namespace now. We can detect
460 # that because Moose will explicitly update the singleton
461 # cache in Class::MOP.
462 my $current_meta = Class::MOP::get_metaclass_by_name($name);
463 return if $current_meta ne $self;
465 my ($serial_id) = ($name =~ /^$ANON_CLASS_PREFIX(\d+)/o);
467 @{$name . '::ISA'} = ();
468 %{$name . '::'} = ();
469 delete ${$ANON_CLASS_PREFIX}{$serial_id . '::'};
471 Class::MOP::remove_metaclass_by_name($name);
476 # creating classes with MOP ...
479 my ( $class, @args ) = @_;
481 unshift @args, 'package' if @args % 2 == 1;
483 my (%options) = @args;
484 my $package_name = $options{package};
486 (ref $options{superclasses} eq 'ARRAY')
487 || confess "You must pass an ARRAY ref of superclasses"
488 if exists $options{superclasses};
490 (ref $options{attributes} eq 'ARRAY')
491 || confess "You must pass an ARRAY ref of attributes"
492 if exists $options{attributes};
494 (ref $options{methods} eq 'HASH')
495 || confess "You must pass a HASH ref of methods"
496 if exists $options{methods};
498 $options{meta_name} = 'meta'
499 unless exists $options{meta_name};
501 my (%initialize_options) = @args;
502 delete @initialize_options{qw(
511 my $meta = $class->initialize( $package_name => %initialize_options );
513 $meta->_instantiate_module( $options{version}, $options{authority} );
515 $meta->_add_meta_method($options{meta_name})
516 if defined $options{meta_name};
518 $meta->superclasses(@{$options{superclasses}})
519 if exists $options{superclasses};
521 # process attributes first, so that they can
522 # install accessors, but locally defined methods
523 # can then overwrite them. It is maybe a little odd, but
524 # I think this should be the order of things.
525 if (exists $options{attributes}) {
526 foreach my $attr (@{$options{attributes}}) {
527 $meta->add_attribute($attr);
530 if (exists $options{methods}) {
531 foreach my $method_name (keys %{$options{methods}}) {
532 $meta->add_method($method_name, $options{methods}->{$method_name});
538 # Instance Construction & Cloning
544 # we need to protect the integrity of the
545 # Class::MOP::Class singletons here, so we
546 # delegate this to &construct_class_instance
547 # which will deal with the singletons
548 return $class->_construct_class_instance(@_)
549 if $class->name->isa('Class::MOP::Class');
550 return $class->_construct_instance(@_);
553 sub _construct_instance {
555 my $params = @_ == 1 ? $_[0] : {@_};
556 my $meta_instance = $class->get_meta_instance();
558 # the code below is almost certainly incorrect
559 # but this is foreign inheritance, so we might
560 # have to kludge it in the end.
562 if (my $instance_class = blessed($params->{__INSTANCE__})) {
563 ($instance_class eq $class->name)
564 || confess "Objects passed as the __INSTANCE__ parameter must "
565 . "already be blessed into the correct class, but "
566 . "$params->{__INSTANCE__} is not a " . $class->name;
567 $instance = $params->{__INSTANCE__};
569 elsif (exists $params->{__INSTANCE__}) {
570 confess "The __INSTANCE__ parameter must be a blessed reference, not "
571 . $params->{__INSTANCE__};
574 $instance = $meta_instance->create_instance();
576 foreach my $attr ($class->get_all_attributes()) {
577 $attr->initialize_instance_slot($meta_instance, $instance, $params);
579 if (Class::MOP::metaclass_is_weak($class->name)) {
580 $meta_instance->_set_mop_slot($instance, $class);
585 sub _inline_new_object {
589 'my $class = shift;',
590 '$class = Scalar::Util::blessed($class) || $class;',
591 $self->_inline_fallback_constructor('$class'),
592 $self->_inline_params('$params', '$class'),
593 $self->_inline_generate_instance('$instance', '$class'),
594 $self->_inline_slot_initializers,
595 $self->_inline_preserve_weak_metaclasses,
596 $self->_inline_extra_init,
601 sub _inline_fallback_constructor {
605 'return ' . $self->_generate_fallback_constructor($class),
606 'if ' . $class . ' ne \'' . $self->name . '\';',
610 sub _generate_fallback_constructor {
613 return 'Class::MOP::Class->initialize(' . $class . ')->new_object(@_)',
618 my ($params, $class) = @_;
620 'my ' . $params . ' = @_ == 1 ? $_[0] : {@_};',
624 sub _inline_generate_instance {
626 my ($inst, $class) = @_;
628 'my ' . $inst . ' = ' . $self->_inline_create_instance($class) . ';',
632 sub _inline_create_instance {
635 return $self->get_meta_instance->inline_create_instance(@_);
638 sub _inline_slot_initializers {
643 return map { $self->_inline_slot_initializer($_, $idx++) }
644 sort { $a->name cmp $b->name } $self->get_all_attributes;
647 sub _inline_slot_initializer {
649 my ($attr, $idx) = @_;
651 if (defined(my $init_arg = $attr->init_arg)) {
653 'if (exists $params->{\'' . $init_arg . '\'}) {',
654 $self->_inline_init_attr_from_constructor($attr, $idx),
657 if (my @default = $self->_inline_init_attr_from_default($attr, $idx)) {
666 elsif (my @default = $self->_inline_init_attr_from_default($attr, $idx)) {
678 sub _inline_init_attr_from_constructor {
680 my ($attr, $idx) = @_;
682 my @initial_value = $attr->_inline_set_value(
683 '$instance', '$params->{\'' . $attr->init_arg . '\'}',
686 push @initial_value, (
687 '$attrs->[' . $idx . ']->set_initial_value(',
689 $attr->_inline_instance_get('$instance'),
691 ) if $attr->has_initializer;
693 return @initial_value;
696 sub _inline_init_attr_from_default {
698 my ($attr, $idx) = @_;
700 my $default = $self->_inline_default_value($attr, $idx);
701 return unless $default;
703 my @initial_value = $attr->_inline_set_value('$instance', $default);
705 push @initial_value, (
706 '$attrs->[' . $idx . ']->set_initial_value(',
708 $attr->_inline_instance_get('$instance'),
710 ) if $attr->has_initializer;
712 return @initial_value;
715 sub _inline_default_value {
717 my ($attr, $index) = @_;
719 if ($attr->has_default) {
721 # default values can either be CODE refs
722 # in which case we need to call them. Or
723 # they can be scalars (strings/numbers)
724 # in which case we can just deal with them
725 # in the code we eval.
726 if ($attr->is_default_a_coderef) {
727 return '$defaults->[' . $index . ']->($instance)';
730 return '$defaults->[' . $index . ']';
733 elsif ($attr->has_builder) {
734 return '$instance->' . $attr->builder;
741 sub _inline_preserve_weak_metaclasses {
743 if (Class::MOP::metaclass_is_weak($self->name)) {
745 $self->_inline_set_mop_slot(
746 '$instance', 'Class::MOP::class_of($class)'
755 sub _inline_extra_init { }
758 sub get_meta_instance {
760 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
763 sub _create_meta_instance {
766 my $instance = $self->instance_metaclass->new(
767 associated_metaclass => $self,
768 attributes => [ $self->get_all_attributes() ],
771 $self->add_meta_instance_dependencies()
772 if $instance->is_dependent_on_superclasses();
777 sub _inline_rebless_instance {
780 return $self->get_meta_instance->inline_rebless_instance_structure(@_);
783 sub _inline_get_mop_slot {
786 return $self->get_meta_instance->_inline_get_mop_slot(@_);
789 sub _inline_set_mop_slot {
792 return $self->get_meta_instance->_inline_set_mop_slot(@_);
795 sub _inline_clear_mop_slot {
798 return $self->get_meta_instance->_inline_clear_mop_slot(@_);
803 my $instance = shift;
804 (blessed($instance) && $instance->isa($class->name))
805 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
808 # we need to protect the integrity of the
809 # Class::MOP::Class singletons here, they
810 # should not be cloned.
811 return $instance if $instance->isa('Class::MOP::Class');
812 $class->_clone_instance($instance, @_);
815 sub _clone_instance {
816 my ($class, $instance, %params) = @_;
818 || confess "You can only clone instances, ($instance) is not a blessed instance";
819 my $meta_instance = $class->get_meta_instance();
820 my $clone = $meta_instance->clone_instance($instance);
821 foreach my $attr ($class->get_all_attributes()) {
822 if ( defined( my $init_arg = $attr->init_arg ) ) {
823 if (exists $params{$init_arg}) {
824 $attr->set_value($clone, $params{$init_arg});
831 sub _force_rebless_instance {
832 my ($self, $instance, %params) = @_;
833 my $old_metaclass = Class::MOP::class_of($instance);
835 $old_metaclass->rebless_instance_away($instance, $self, %params)
838 my $meta_instance = $self->get_meta_instance;
840 if (Class::MOP::metaclass_is_weak($old_metaclass->name)) {
841 $meta_instance->_clear_mop_slot($instance);
845 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
846 $meta_instance->rebless_instance_structure($_[1], $self);
848 $self->_fixup_attributes_after_rebless($instance, $old_metaclass, %params);
850 if (Class::MOP::metaclass_is_weak($self->name)) {
851 $meta_instance->_set_mop_slot($instance, $self);
855 sub rebless_instance {
856 my ($self, $instance, %params) = @_;
857 my $old_metaclass = Class::MOP::class_of($instance);
859 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
860 $self->name->isa($old_class)
861 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
863 $self->_force_rebless_instance($_[1], %params);
868 sub rebless_instance_back {
869 my ( $self, $instance ) = @_;
870 my $old_metaclass = Class::MOP::class_of($instance);
873 = $old_metaclass ? $old_metaclass->name : blessed($instance);
874 $old_class->isa( $self->name )
876 "You may rebless only into a superclass of ($old_class), of which ("
880 $self->_force_rebless_instance($_[1]);
885 sub rebless_instance_away {
886 # this intentionally does nothing, it is just a hook
889 sub _fixup_attributes_after_rebless {
891 my ($instance, $rebless_from, %params) = @_;
892 my $meta_instance = $self->get_meta_instance;
894 for my $attr ( $rebless_from->get_all_attributes ) {
895 next if $self->find_attribute_by_name( $attr->name );
896 $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
899 foreach my $attr ( $self->get_all_attributes ) {
900 if ( $attr->has_value($instance) ) {
901 if ( defined( my $init_arg = $attr->init_arg ) ) {
902 $params{$init_arg} = $attr->get_value($instance)
903 unless exists $params{$init_arg};
906 $attr->set_value($instance, $attr->get_value($instance));
911 foreach my $attr ($self->get_all_attributes) {
912 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
916 sub _attach_attribute {
917 my ($self, $attribute) = @_;
918 $attribute->attach_to_class($self);
921 sub _post_add_attribute {
922 my ( $self, $attribute ) = @_;
924 $self->invalidate_meta_instances;
926 # invalidate package flag here
929 $attribute->install_accessors;
932 $self->remove_attribute( $attribute->name );
937 sub remove_attribute {
940 my $removed_attribute = $self->SUPER::remove_attribute(@_)
943 $self->invalidate_meta_instances;
945 $removed_attribute->remove_accessors;
946 $removed_attribute->detach_from_class;
948 return$removed_attribute;
951 sub find_attribute_by_name {
952 my ( $self, $attr_name ) = @_;
954 foreach my $class ( $self->linearized_isa ) {
955 # fetch the meta-class ...
956 my $meta = Class::MOP::Class->initialize($class);
957 return $meta->get_attribute($attr_name)
958 if $meta->has_attribute($attr_name);
964 sub get_all_attributes {
966 my %attrs = map { %{ Class::MOP::Class->initialize($_)->_attribute_map } }
967 reverse $self->linearized_isa;
968 return values %attrs;
976 my $isa = $self->get_or_add_package_symbol('@ISA');
983 # on 5.8 and below, we need to call
984 # a method to get Perl to detect
985 # a cycle in the class hierarchy
986 my $class = $self->name;
990 # we need to check the metaclass
991 # compatibility here so that we can
992 # be sure that the superclass is
993 # not potentially creating an issues
994 # we don't know about
996 $self->_check_metaclass_compatibility();
997 $self->_superclasses_updated();
1003 sub _superclasses_updated {
1005 $self->update_meta_instance_dependencies();
1006 # keep strong references to all our parents, so they don't disappear if
1007 # they are anon classes and don't have any direct instances
1008 $self->_superclass_metas(
1009 map { Class::MOP::class_of($_) } $self->superclasses
1013 sub _superclass_metas {
1015 $self->{_superclass_metas} = [@_];
1020 my $super_class = $self->name;
1022 return @{ $super_class->mro::get_isarev() };
1025 sub direct_subclasses {
1027 my $super_class = $self->name;
1032 } Class::MOP::Class->initialize($_)->superclasses
1033 } $self->subclasses;
1036 sub linearized_isa {
1037 return @{ mro::get_linear_isa( (shift)->name ) };
1040 sub class_precedence_list {
1042 my $name = $self->name;
1044 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
1046 # We need to check for circular inheritance here
1047 # if we are are not on 5.10, cause 5.8 detects it
1048 # late. This will do nothing if all is well, and
1049 # blow up otherwise. Yes, it's an ugly hack, better
1050 # suggestions are welcome.
1052 ($name || return)->isa('This is a test for circular inheritance')
1055 # if our mro is c3, we can
1056 # just grab the linear_isa
1057 if (mro::get_mro($name) eq 'c3') {
1058 return @{ mro::get_linear_isa($name) }
1062 # we can't grab the linear_isa for dfs
1063 # since it has all the duplicates
1068 Class::MOP::Class->initialize($_)->class_precedence_list()
1069 } $self->superclasses()
1077 my $fetch_and_prepare_method = sub {
1078 my ($self, $method_name) = @_;
1079 my $wrapped_metaclass = $self->wrapped_method_metaclass;
1081 my $method = $self->get_method($method_name);
1082 # if we dont have local ...
1084 # try to find the next method
1085 $method = $self->find_next_method_by_name($method_name);
1086 # die if it does not exist
1088 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
1089 # and now make sure to wrap it
1090 # even if it is already wrapped
1091 # because we need a new sub ref
1092 $method = $wrapped_metaclass->wrap($method,
1093 package_name => $self->name,
1094 name => $method_name,
1098 # now make sure we wrap it properly
1099 $method = $wrapped_metaclass->wrap($method,
1100 package_name => $self->name,
1101 name => $method_name,
1102 ) unless $method->isa($wrapped_metaclass);
1104 $self->add_method($method_name => $method);
1108 sub add_before_method_modifier {
1109 my ($self, $method_name, $method_modifier) = @_;
1110 (defined $method_name && length $method_name)
1111 || confess "You must pass in a method name";
1112 my $method = $fetch_and_prepare_method->($self, $method_name);
1113 $method->add_before_modifier(
1114 subname(':before' => $method_modifier)
1118 sub add_after_method_modifier {
1119 my ($self, $method_name, $method_modifier) = @_;
1120 (defined $method_name && length $method_name)
1121 || confess "You must pass in a method name";
1122 my $method = $fetch_and_prepare_method->($self, $method_name);
1123 $method->add_after_modifier(
1124 subname(':after' => $method_modifier)
1128 sub add_around_method_modifier {
1129 my ($self, $method_name, $method_modifier) = @_;
1130 (defined $method_name && length $method_name)
1131 || confess "You must pass in a method name";
1132 my $method = $fetch_and_prepare_method->($self, $method_name);
1133 $method->add_around_modifier(
1134 subname(':around' => $method_modifier)
1139 # the methods above used to be named like this:
1140 # ${pkg}::${method}:(before|after|around)
1141 # but this proved problematic when using one modifier
1142 # to wrap multiple methods (something which is likely
1143 # to happen pretty regularly IMO). So instead of naming
1144 # it like this, I have chosen to just name them purely
1145 # with their modifier names, like so:
1146 # :(before|after|around)
1147 # The fact is that in a stack trace, it will be fairly
1148 # evident from the context what method they are attached
1149 # to, and so don't need the fully qualified name.
1152 sub find_method_by_name {
1153 my ($self, $method_name) = @_;
1154 (defined $method_name && length $method_name)
1155 || confess "You must define a method name to find";
1156 foreach my $class ($self->linearized_isa) {
1157 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1158 return $method if defined $method;
1163 sub get_all_methods {
1167 for my $class ( reverse $self->linearized_isa ) {
1168 my $meta = Class::MOP::Class->initialize($class);
1170 $methods{ $_->name } = $_ for $meta->_get_local_methods;
1173 return values %methods;
1176 sub get_all_method_names {
1179 return grep { !$uniq{$_}++ } map { Class::MOP::Class->initialize($_)->get_method_list } $self->linearized_isa;
1182 sub find_all_methods_by_name {
1183 my ($self, $method_name) = @_;
1184 (defined $method_name && length $method_name)
1185 || confess "You must define a method name to find";
1187 foreach my $class ($self->linearized_isa) {
1188 # fetch the meta-class ...
1189 my $meta = Class::MOP::Class->initialize($class);
1191 name => $method_name,
1193 code => $meta->get_method($method_name)
1194 } if $meta->has_method($method_name);
1199 sub find_next_method_by_name {
1200 my ($self, $method_name) = @_;
1201 (defined $method_name && length $method_name)
1202 || confess "You must define a method name to find";
1203 my @cpl = $self->linearized_isa;
1204 shift @cpl; # discard ourselves
1205 foreach my $class (@cpl) {
1206 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1207 return $method if defined $method;
1212 sub update_meta_instance_dependencies {
1215 if ( $self->{meta_instance_dependencies} ) {
1216 return $self->add_meta_instance_dependencies;
1220 sub add_meta_instance_dependencies {
1223 $self->remove_meta_instance_dependencies;
1225 my @attrs = $self->get_all_attributes();
1228 my @classes = grep { not $seen{ $_->name }++ }
1229 map { $_->associated_class } @attrs;
1231 foreach my $class (@classes) {
1232 $class->add_dependent_meta_instance($self);
1235 $self->{meta_instance_dependencies} = \@classes;
1238 sub remove_meta_instance_dependencies {
1241 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
1242 foreach my $class (@$classes) {
1243 $class->remove_dependent_meta_instance($self);
1253 sub add_dependent_meta_instance {
1254 my ( $self, $metaclass ) = @_;
1255 push @{ $self->{dependent_meta_instances} }, $metaclass;
1258 sub remove_dependent_meta_instance {
1259 my ( $self, $metaclass ) = @_;
1260 my $name = $metaclass->name;
1261 @$_ = grep { $_->name ne $name } @$_
1262 for $self->{dependent_meta_instances};
1265 sub invalidate_meta_instances {
1267 $_->invalidate_meta_instance()
1268 for $self, @{ $self->{dependent_meta_instances} };
1271 sub invalidate_meta_instance {
1273 undef $self->{_meta_instance};
1276 # check if we can reinitialize
1280 # if any local attr is defined
1281 return if $self->get_attribute_list;
1283 # or any non-declared methods
1284 for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1285 return if $method->isa("Class::MOP::Method::Generated");
1286 # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1294 sub is_mutable { 1 }
1295 sub is_immutable { 0 }
1297 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1299 sub _immutable_options {
1300 my ( $self, @args ) = @_;
1303 inline_accessors => 1,
1304 inline_constructor => 1,
1305 inline_destructor => 0,
1307 immutable_trait => $self->immutable_trait,
1308 constructor_name => $self->constructor_name,
1309 constructor_class => $self->constructor_class,
1310 destructor_class => $self->destructor_class,
1315 sub make_immutable {
1316 my ( $self, @args ) = @_;
1318 if ( $self->is_mutable ) {
1319 $self->_initialize_immutable( $self->_immutable_options(@args) );
1320 $self->_rebless_as_immutable(@args);
1331 if ( $self->is_immutable ) {
1332 my @args = $self->immutable_options;
1333 $self->_rebless_as_mutable();
1334 $self->_remove_inlined_code(@args);
1335 delete $self->{__immutable};
1343 sub _rebless_as_immutable {
1344 my ( $self, @args ) = @_;
1346 $self->{__immutable}{original_class} = ref $self;
1348 bless $self => $self->_immutable_metaclass(@args);
1351 sub _immutable_metaclass {
1352 my ( $self, %args ) = @_;
1354 if ( my $class = $args{immutable_metaclass} ) {
1358 my $trait = $args{immutable_trait} = $self->immutable_trait
1359 || confess "no immutable trait specified for $self";
1361 my $meta = $self->meta;
1362 my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1366 if ( $meta_attr and $trait eq $meta_attr->default ) {
1367 # if the trait is the same as the default we try and pick a
1368 # predictable name for the immutable metaclass
1369 $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1372 $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1373 $trait, 'ForMetaClass', ref($self);
1377 if Class::MOP::is_class_loaded($class_name);
1379 # If the metaclass is a subclass of CMOP::Class which has had
1380 # metaclass roles applied (via Moose), then we want to make sure
1381 # that we preserve that anonymous class (see Fey::ORM for an
1382 # example of where this matters).
1383 my $meta_name = $meta->_real_ref_name;
1385 my $immutable_meta = $meta_name->create(
1387 superclasses => [ ref $self ],
1390 Class::MOP::MiniTrait::apply( $immutable_meta, $trait );
1392 $immutable_meta->make_immutable(
1393 inline_constructor => 0,
1394 inline_accessors => 0,
1400 sub _remove_inlined_code {
1403 $self->remove_method( $_->name ) for $self->_inlined_methods;
1405 delete $self->{__immutable}{inlined_methods};
1408 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1410 sub _add_inlined_method {
1411 my ( $self, $method ) = @_;
1413 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1416 sub _initialize_immutable {
1417 my ( $self, %args ) = @_;
1419 $self->{__immutable}{options} = \%args;
1420 $self->_install_inlined_code(%args);
1423 sub _install_inlined_code {
1424 my ( $self, %args ) = @_;
1427 $self->_inline_accessors(%args) if $args{inline_accessors};
1428 $self->_inline_constructor(%args) if $args{inline_constructor};
1429 $self->_inline_destructor(%args) if $args{inline_destructor};
1432 sub _rebless_as_mutable {
1435 bless $self, $self->_get_mutable_metaclass_name;
1440 sub _inline_accessors {
1443 foreach my $attr_name ( $self->get_attribute_list ) {
1444 $self->get_attribute($attr_name)->install_accessors(1);
1448 sub _inline_constructor {
1449 my ( $self, %args ) = @_;
1451 my $name = $args{constructor_name};
1452 # A class may not even have a constructor, and that's okay.
1453 return unless defined $name;
1455 if ( $self->has_method($name) && !$args{replace_constructor} ) {
1456 my $class = $self->name;
1457 warn "Not inlining a constructor for $class since it defines"
1458 . " its own constructor.\n"
1459 . "If you are certain you don't need to inline your"
1460 . " constructor, specify inline_constructor => 0 in your"
1461 . " call to $class->meta->make_immutable\n";
1465 my $constructor_class = $args{constructor_class};
1467 Class::MOP::load_class($constructor_class);
1469 my $constructor = $constructor_class->new(
1473 package_name => $self->name,
1477 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1478 $self->add_method( $name => $constructor );
1479 $self->_add_inlined_method($constructor);
1483 sub _inline_destructor {
1484 my ( $self, %args ) = @_;
1486 ( exists $args{destructor_class} && defined $args{destructor_class} )
1487 || confess "The 'inline_destructor' option is present, but "
1488 . "no destructor class was specified";
1490 if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1491 my $class = $self->name;
1492 warn "Not inlining a destructor for $class since it defines"
1493 . " its own destructor.\n";
1497 my $destructor_class = $args{destructor_class};
1499 Class::MOP::load_class($destructor_class);
1501 return unless $destructor_class->is_needed($self);
1503 my $destructor = $destructor_class->new(
1506 package_name => $self->name,
1510 if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1511 $self->add_method( 'DESTROY' => $destructor );
1512 $self->_add_inlined_method($destructor);
1518 # ABSTRACT: Class Meta Object
1526 # assuming that class Foo
1527 # has been defined, you can
1529 # use this for introspection ...
1531 # add a method to Foo ...
1532 Foo->meta->add_method( 'bar' => sub {...} )
1534 # get a list of all the classes searched
1535 # the method dispatcher in the correct order
1536 Foo->meta->class_precedence_list()
1538 # remove a method from Foo
1539 Foo->meta->remove_method('bar');
1541 # or use this to actually create classes ...
1543 Class::MOP::Class->create(
1546 superclasses => ['Foo'],
1548 Class::MOP::Attribute->new('$bar'),
1549 Class::MOP::Attribute->new('$baz'),
1552 calculate_bar => sub {...},
1553 construct_baz => sub {...}
1560 The Class Protocol is the largest and most complex part of the
1561 Class::MOP meta-object protocol. It controls the introspection and
1562 manipulation of Perl 5 classes, and it can create them as well. The
1563 best way to understand what this module can do is to read the
1564 documentation for each of its methods.
1568 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1572 =head2 Class construction
1574 These methods all create new C<Class::MOP::Class> objects. These
1575 objects can represent existing classes or they can be used to create
1576 new classes from scratch.
1578 The metaclass object for a given class is a singleton. If you attempt
1579 to create a metaclass for the same class twice, you will just get the
1584 =item B<< Class::MOP::Class->create($package_name, %options) >>
1586 This method creates a new C<Class::MOP::Class> object with the given
1587 package name. It accepts a number of options:
1593 An optional version number for the newly created package.
1597 An optional authority for the newly created package.
1599 =item * superclasses
1601 An optional array reference of superclass names.
1605 An optional hash reference of methods for the class. The keys of the
1606 hash reference are method names and values are subroutine references.
1610 An optional array reference of L<Class::MOP::Attribute> objects.
1614 Specifies the name to install the C<meta> method for this class under.
1615 If it is not passed, C<meta> is assumed, and if C<undef> is explicitly
1616 given, no meta method will be installed.
1620 If true, the metaclass that is stored in the global cache will be a
1623 Classes created in this way are destroyed once the metaclass they are
1624 attached to goes out of scope, and will be removed from Perl's internal
1627 All instances of a class with a weakened metaclass keep a special
1628 reference to the metaclass object, which prevents the metaclass from
1629 going out of scope while any instances exist.
1631 This only works if the instance is based on a hash reference, however.
1635 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1637 This method works just like C<< Class::MOP::Class->create >> but it
1638 creates an "anonymous" class. In fact, the class does have a name, but
1639 that name is a unique name generated internally by this module.
1641 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1642 parameters that C<create> accepts.
1644 Anonymous classes default to C<< weaken => 1 >>, although this can be
1647 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1649 This method will initialize a C<Class::MOP::Class> object for the
1650 named package. Unlike C<create>, this method I<will not> create a new
1653 The purpose of this method is to retrieve a C<Class::MOP::Class>
1654 object for introspecting an existing class.
1656 If an existing C<Class::MOP::Class> object exists for the named
1657 package, it will be returned, and any options provided will be
1660 If the object does not yet exist, it will be created.
1662 The valid options that can be passed to this method are
1663 C<attribute_metaclass>, C<method_metaclass>,
1664 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1665 optional, and default to the appropriate class in the C<Class::MOP>
1670 =head2 Object instance construction and cloning
1672 These methods are all related to creating and/or cloning object
1677 =item B<< $metaclass->clone_object($instance, %params) >>
1679 This method clones an existing object instance. Any parameters you
1680 provide are will override existing attribute values in the object.
1682 This is a convenience method for cloning an object instance, then
1683 blessing it into the appropriate package.
1685 You could implement a clone method in your class, using this method:
1688 my ($self, %params) = @_;
1689 $self->meta->clone_object($self, %params);
1692 =item B<< $metaclass->rebless_instance($instance, %params) >>
1694 This method changes the class of C<$instance> to the metaclass's class.
1696 You can only rebless an instance into a subclass of its current
1697 class. If you pass any additional parameters, these will be treated
1698 like constructor parameters and used to initialize the object's
1699 attributes. Any existing attributes that are already set will be
1702 Before reblessing the instance, this method will call
1703 C<rebless_instance_away> on the instance's current metaclass. This method
1704 will be passed the instance, the new metaclass, and any parameters
1705 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1706 does nothing; it is merely a hook.
1708 =item B<< $metaclass->rebless_instance_back($instance) >>
1710 Does the same thing as C<rebless_instance>, except that you can only
1711 rebless an instance into one of its superclasses. Any attributes that
1712 do not exist in the superclass will be deinitialized.
1714 This is a much more dangerous operation than C<rebless_instance>,
1715 especially when multiple inheritance is involved, so use this carefully!
1717 =item B<< $metaclass->new_object(%params) >>
1719 This method is used to create a new object of the metaclass's
1720 class. Any parameters you provide are used to initialize the
1721 instance's attributes. A special C<__INSTANCE__> key can be passed to
1722 provide an already generated instance, rather than having Class::MOP
1723 generate it for you. This is mostly useful for using Class::MOP with
1724 foreign classes which generate instances using their own constructors.
1726 =item B<< $metaclass->instance_metaclass >>
1728 Returns the class name of the instance metaclass. See
1729 L<Class::MOP::Instance> for more information on the instance
1732 =item B<< $metaclass->get_meta_instance >>
1734 Returns an instance of the C<instance_metaclass> to be used in the
1735 construction of a new instance of the class.
1739 =head2 Informational predicates
1741 These are a few predicate methods for asking information about the
1746 =item B<< $metaclass->is_anon_class >>
1748 This returns true if the class was created by calling C<<
1749 Class::MOP::Class->create_anon_class >>.
1751 =item B<< $metaclass->is_mutable >>
1753 This returns true if the class is still mutable.
1755 =item B<< $metaclass->is_immutable >>
1757 This returns true if the class has been made immutable.
1759 =item B<< $metaclass->is_pristine >>
1761 A class is I<not> pristine if it has non-inherited attributes or if it
1762 has any generated methods.
1766 =head2 Inheritance Relationships
1770 =item B<< $metaclass->superclasses(@superclasses) >>
1772 This is a read-write accessor which represents the superclass
1773 relationships of the metaclass's class.
1775 This is basically sugar around getting and setting C<@ISA>.
1777 =item B<< $metaclass->class_precedence_list >>
1779 This returns a list of all of the class's ancestor classes. The
1780 classes are returned in method dispatch order.
1782 =item B<< $metaclass->linearized_isa >>
1784 This returns a list based on C<class_precedence_list> but with all
1787 =item B<< $metaclass->subclasses >>
1789 This returns a list of all subclasses for this class, even indirect
1792 =item B<< $metaclass->direct_subclasses >>
1794 This returns a list of immediate subclasses for this class, which does not
1795 include indirect subclasses.
1799 =head2 Method introspection and creation
1801 These methods allow you to introspect a class's methods, as well as
1802 add, remove, or change methods.
1804 Determining what is truly a method in a Perl 5 class requires some
1805 heuristics (aka guessing).
1807 Methods defined outside the package with a fully qualified name (C<sub
1808 Package::name { ... }>) will be included. Similarly, methods named
1809 with a fully qualified name using L<Sub::Name> are also included.
1811 However, we attempt to ignore imported functions.
1813 Ultimately, we are using heuristics to determine what truly is a
1814 method in a class, and these heuristics may get the wrong answer in
1815 some edge cases. However, for most "normal" cases the heuristics work
1820 =item B<< $metaclass->get_method($method_name) >>
1822 This will return a L<Class::MOP::Method> for the specified
1823 C<$method_name>. If the class does not have the specified method, it
1826 =item B<< $metaclass->has_method($method_name) >>
1828 Returns a boolean indicating whether or not the class defines the
1829 named method. It does not include methods inherited from parent
1832 =item B<< $metaclass->get_method_list >>
1834 This will return a list of method I<names> for all methods defined in
1837 =item B<< $metaclass->add_method($method_name, $method) >>
1839 This method takes a method name and a subroutine reference, and adds
1840 the method to the class.
1842 The subroutine reference can be a L<Class::MOP::Method>, and you are
1843 strongly encouraged to pass a meta method object instead of a code
1844 reference. If you do so, that object gets stored as part of the
1845 class's method map directly. If not, the meta information will have to
1846 be recreated later, and may be incorrect.
1848 If you provide a method object, this method will clone that object if
1849 the object's package name does not match the class name. This lets us
1850 track the original source of any methods added from other classes
1851 (notably Moose roles).
1853 =item B<< $metaclass->remove_method($method_name) >>
1855 Remove the named method from the class. This method returns the
1856 L<Class::MOP::Method> object for the method.
1858 =item B<< $metaclass->method_metaclass >>
1860 Returns the class name of the method metaclass, see
1861 L<Class::MOP::Method> for more information on the method metaclass.
1863 =item B<< $metaclass->wrapped_method_metaclass >>
1865 Returns the class name of the wrapped method metaclass, see
1866 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1869 =item B<< $metaclass->get_all_methods >>
1871 This will traverse the inheritance hierarchy and return a list of all
1872 the L<Class::MOP::Method> objects for this class and its parents.
1874 =item B<< $metaclass->find_method_by_name($method_name) >>
1876 This will return a L<Class::MOP::Method> for the specified
1877 C<$method_name>. If the class does not have the specified method, it
1880 Unlike C<get_method>, this method I<will> look for the named method in
1883 =item B<< $metaclass->get_all_method_names >>
1885 This will return a list of method I<names> for all of this class's
1886 methods, including inherited methods.
1888 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1890 This method looks for the named method in the class and all of its
1891 parents. It returns every matching method it finds in the inheritance
1892 tree, so it returns a list of methods.
1894 Each method is returned as a hash reference with three keys. The keys
1895 are C<name>, C<class>, and C<code>. The C<code> key has a
1896 L<Class::MOP::Method> object as its value.
1898 The list of methods is distinct.
1900 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1902 This method returns the first method in any superclass matching the
1903 given name. It is effectively the method that C<SUPER::$method_name>
1908 =head2 Attribute introspection and creation
1910 Because Perl 5 does not have a core concept of attributes in classes,
1911 we can only return information about attributes which have been added
1912 via this class's methods. We cannot discover information about
1913 attributes which are defined in terms of "regular" Perl 5 methods.
1917 =item B<< $metaclass->get_attribute($attribute_name) >>
1919 This will return a L<Class::MOP::Attribute> for the specified
1920 C<$attribute_name>. If the class does not have the specified
1921 attribute, it returns C<undef>.
1923 NOTE that get_attribute does not search superclasses, for that you
1924 need to use C<find_attribute_by_name>.
1926 =item B<< $metaclass->has_attribute($attribute_name) >>
1928 Returns a boolean indicating whether or not the class defines the
1929 named attribute. It does not include attributes inherited from parent
1932 =item B<< $metaclass->get_attribute_list >>
1934 This will return a list of attributes I<names> for all attributes
1935 defined in this class. Note that this operates on the current class
1936 only, it does not traverse the inheritance hierarchy.
1938 =item B<< $metaclass->get_all_attributes >>
1940 This will traverse the inheritance hierarchy and return a list of all
1941 the L<Class::MOP::Attribute> objects for this class and its parents.
1943 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1945 This will return a L<Class::MOP::Attribute> for the specified
1946 C<$attribute_name>. If the class does not have the specified
1947 attribute, it returns C<undef>.
1949 Unlike C<get_attribute>, this attribute I<will> look for the named
1950 attribute in superclasses.
1952 =item B<< $metaclass->add_attribute(...) >>
1954 This method accepts either an existing L<Class::MOP::Attribute>
1955 object or parameters suitable for passing to that class's C<new>
1958 The attribute provided will be added to the class.
1960 Any accessor methods defined by the attribute will be added to the
1961 class when the attribute is added.
1963 If an attribute of the same name already exists, the old attribute
1964 will be removed first.
1966 =item B<< $metaclass->remove_attribute($attribute_name) >>
1968 This will remove the named attribute from the class, and
1969 L<Class::MOP::Attribute> object.
1971 Removing an attribute also removes any accessor methods defined by the
1974 However, note that removing an attribute will only affect I<future>
1975 object instances created for this class, not existing instances.
1977 =item B<< $metaclass->attribute_metaclass >>
1979 Returns the class name of the attribute metaclass for this class. By
1980 default, this is L<Class::MOP::Attribute>.
1984 =head2 Class Immutability
1986 Making a class immutable "freezes" the class definition. You can no
1987 longer call methods which alter the class, such as adding or removing
1988 methods or attributes.
1990 Making a class immutable lets us optimize the class by inlining some
1991 methods, and also allows us to optimize some methods on the metaclass
1994 After immutabilization, the metaclass object will cache most informational
1995 methods that returns information about methods or attributes. Methods which
1996 would alter the class, such as C<add_attribute> and C<add_method>, will
1997 throw an error on an immutable metaclass object.
1999 The immutabilization system in L<Moose> takes much greater advantage
2000 of the inlining features than Class::MOP itself does.
2004 =item B<< $metaclass->make_immutable(%options) >>
2006 This method will create an immutable transformer and use it to make
2007 the class and its metaclass object immutable.
2009 This method accepts the following options:
2013 =item * inline_accessors
2015 =item * inline_constructor
2017 =item * inline_destructor
2019 These are all booleans indicating whether the specified method(s)
2022 By default, accessors and the constructor are inlined, but not the
2025 =item * immutable_trait
2027 The name of a class which will be used as a parent class for the
2028 metaclass object being made immutable. This "trait" implements the
2029 post-immutability functionality of the metaclass (but not the
2030 transformation itself).
2032 This defaults to L<Class::MOP::Class::Immutable::Trait>.
2034 =item * constructor_name
2036 This is the constructor method name. This defaults to "new".
2038 =item * constructor_class
2040 The name of the method metaclass for constructors. It will be used to
2041 generate the inlined constructor. This defaults to
2042 "Class::MOP::Method::Constructor".
2044 =item * replace_constructor
2046 This is a boolean indicating whether an existing constructor should be
2047 replaced when inlining a constructor. This defaults to false.
2049 =item * destructor_class
2051 The name of the method metaclass for destructors. It will be used to
2052 generate the inlined destructor. This defaults to
2053 "Class::MOP::Method::Denstructor".
2055 =item * replace_destructor
2057 This is a boolean indicating whether an existing destructor should be
2058 replaced when inlining a destructor. This defaults to false.
2062 =item B<< $metaclass->immutable_options >>
2064 Returns a hash of the options used when making the class immutable, including
2065 both defaults and anything supplied by the user in the call to C<<
2066 $metaclass->make_immutable >>. This is useful if you need to temporarily make
2067 a class mutable and then restore immutability as it was before.
2069 =item B<< $metaclass->make_mutable >>
2071 Calling this method reverse the immutabilization transformation.
2075 =head2 Method Modifiers
2077 Method modifiers are hooks which allow a method to be wrapped with
2078 I<before>, I<after> and I<around> method modifiers. Every time a
2079 method is called, its modifiers are also called.
2081 A class can modify its own methods, as well as methods defined in
2084 =head3 How method modifiers work?
2086 Method modifiers work by wrapping the original method and then
2087 replacing it in the class's symbol table. The wrappers will handle
2088 calling all the modifiers in the appropriate order and preserving the
2089 calling context for the original method.
2091 The return values of C<before> and C<after> modifiers are
2092 ignored. This is because their purpose is B<not> to filter the input
2093 and output of the primary method (this is done with an I<around>
2096 This may seem like an odd restriction to some, but doing this allows
2097 for simple code to be added at the beginning or end of a method call
2098 without altering the function of the wrapped method or placing any
2099 extra responsibility on the code of the modifier.
2101 Of course if you have more complex needs, you can use the C<around>
2102 modifier which allows you to change both the parameters passed to the
2103 wrapped method, as well as its return value.
2105 Before and around modifiers are called in last-defined-first-called
2106 order, while after modifiers are called in first-defined-first-called
2107 order. So the call tree might looks something like this:
2119 =head3 What is the performance impact?
2121 Of course there is a performance cost associated with method
2122 modifiers, but we have made every effort to make that cost directly
2123 proportional to the number of modifier features you use.
2125 The wrapping method does its best to B<only> do as much work as it
2126 absolutely needs to. In order to do this we have moved some of the
2127 performance costs to set-up time, where they are easier to amortize.
2129 All this said, our benchmarks have indicated the following:
2131 simple wrapper with no modifiers 100% slower
2132 simple wrapper with simple before modifier 400% slower
2133 simple wrapper with simple after modifier 450% slower
2134 simple wrapper with simple around modifier 500-550% slower
2135 simple wrapper with all 3 modifiers 1100% slower
2137 These numbers may seem daunting, but you must remember, every feature
2138 comes with some cost. To put things in perspective, just doing a
2139 simple C<AUTOLOAD> which does nothing but extract the name of the
2140 method called and return it costs about 400% over a normal method
2145 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
2147 This wraps the specified method with the supplied subroutine
2148 reference. The modifier will be called as a method itself, and will
2149 receive the same arguments as are passed to the method.
2151 When the modifier exits, the wrapped method will be called.
2153 The return value of the modifier will be ignored.
2155 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
2157 This wraps the specified method with the supplied subroutine
2158 reference. The modifier will be called as a method itself, and will
2159 receive the same arguments as are passed to the method.
2161 When the wrapped methods exits, the modifier will be called.
2163 The return value of the modifier will be ignored.
2165 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
2167 This wraps the specified method with the supplied subroutine
2170 The first argument passed to the modifier will be a subroutine
2171 reference to the wrapped method. The second argument is the object,
2172 and after that come any arguments passed when the method is called.
2174 The around modifier can choose to call the original method, as well as
2175 what arguments to pass if it does so.
2177 The return value of the modifier is what will be seen by the caller.
2181 =head2 Introspection
2185 =item B<< Class::MOP::Class->meta >>
2187 This will return a L<Class::MOP::Class> instance for this class.
2189 It should also be noted that L<Class::MOP> will actually bootstrap
2190 this module by installing a number of attribute meta-objects into its