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 Class::Load 'is_class_loaded', 'load_class';
15 use Scalar::Util 'blessed', 'reftype', 'weaken';
16 use Sub::Name 'subname';
18 use List::MoreUtils 'all';
20 use base 'Class::MOP::Module',
21 'Class::MOP::Mixin::HasAttributes',
22 'Class::MOP::Mixin::HasMethods';
32 $package_name = shift;
35 $package_name = $options{package};
38 ($package_name && !ref($package_name))
39 || confess "You must pass a package name and it cannot be blessed";
41 return Class::MOP::get_metaclass_by_name($package_name)
42 || $class->_construct_class_instance(package => $package_name, @_);
46 my ( $class, @args ) = @_;
47 unshift @args, "package" if @args % 2;
49 my $old_metaclass = blessed($options{package})
51 : Class::MOP::get_metaclass_by_name($options{package});
52 $options{weaken} = Class::MOP::metaclass_is_weak($old_metaclass->name)
53 if !exists $options{weaken}
54 && blessed($old_metaclass)
55 && $old_metaclass->isa('Class::MOP::Class');
56 $old_metaclass->_remove_generated_metaobjects
57 if $old_metaclass && $old_metaclass->isa('Class::MOP::Class');
58 my $new_metaclass = $class->SUPER::reinitialize(%options);
59 $new_metaclass->_restore_metaobjects_from($old_metaclass)
60 if $old_metaclass && $old_metaclass->isa('Class::MOP::Class');
61 return $new_metaclass;
64 # NOTE: (meta-circularity)
65 # this is a special form of _construct_instance
66 # (see below), which is used to construct class
67 # meta-object instances for any Class::MOP::*
68 # class. All other classes will use the more
69 # normal &construct_instance.
70 sub _construct_class_instance {
72 my $options = @_ == 1 ? $_[0] : {@_};
73 my $package_name = $options->{package};
74 (defined $package_name && $package_name)
75 || confess "You must pass a package name";
77 # return the metaclass if we have it cached,
78 # and it is still defined (it has not been
79 # reaped by DESTROY yet, which can happen
80 # annoyingly enough during global destruction)
82 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
88 ? $class->_real_ref_name
91 # now create the metaclass
93 if ($class eq 'Class::MOP::Class') {
94 $meta = $class->_new($options);
98 # it is safe to use meta here because
99 # class will always be a subclass of
100 # Class::MOP::Class, which defines meta
101 $meta = $class->meta->_construct_instance($options)
104 # and check the metaclass compatibility
105 $meta->_check_metaclass_compatibility();
107 Class::MOP::store_metaclass_by_name($package_name, $meta);
110 # we need to weaken any anon classes
111 # so that they can call DESTROY properly
112 Class::MOP::weaken_metaclass($package_name) if $options->{weaken};
120 # NOTE: we need to deal with the possibility of class immutability here,
121 # and then get the name of the class appropriately
122 return $self->is_immutable
123 ? $self->_get_mutable_metaclass_name()
130 return Class::MOP::Class->initialize($class)->new_object(@_)
131 if $class ne __PACKAGE__;
133 my $options = @_ == 1 ? $_[0] : {@_};
136 # inherited from Class::MOP::Package
137 'package' => $options->{package},
140 # since the following attributes will
141 # actually be loaded from the symbol
142 # table, and actually bypass the instance
143 # entirely, we can just leave these things
144 # listed here for reference, because they
145 # should not actually have a value associated
147 'namespace' => \undef,
150 # inherited from Class::MOP::Module
152 'authority' => \undef,
154 # defined in Class::MOP::Class
155 'superclasses' => \undef,
158 'attribute_metaclass' =>
159 ( $options->{'attribute_metaclass'} || 'Class::MOP::Attribute' ),
160 'method_metaclass' =>
161 ( $options->{'method_metaclass'} || 'Class::MOP::Method' ),
162 'wrapped_method_metaclass' => (
163 $options->{'wrapped_method_metaclass'}
164 || 'Class::MOP::Method::Wrapped'
166 'instance_metaclass' =>
167 ( $options->{'instance_metaclass'} || 'Class::MOP::Instance' ),
168 'immutable_trait' => (
169 $options->{'immutable_trait'}
170 || 'Class::MOP::Class::Immutable::Trait'
172 'constructor_name' => ( $options->{constructor_name} || 'new' ),
173 'constructor_class' => (
174 $options->{constructor_class} || 'Class::MOP::Method::Constructor'
176 'destructor_class' => $options->{destructor_class},
180 ## Metaclass compatibility
182 my %base_metaclass = (
183 attribute_metaclass => 'Class::MOP::Attribute',
184 method_metaclass => 'Class::MOP::Method',
185 wrapped_method_metaclass => 'Class::MOP::Method::Wrapped',
186 instance_metaclass => 'Class::MOP::Instance',
187 constructor_class => 'Class::MOP::Method::Constructor',
188 destructor_class => 'Class::MOP::Method::Destructor',
191 sub _base_metaclasses { %base_metaclass }
194 sub _check_metaclass_compatibility {
197 my @superclasses = $self->superclasses
200 $self->_fix_metaclass_incompatibility(@superclasses);
202 my %base_metaclass = $self->_base_metaclasses;
204 # this is always okay ...
206 if ref($self) eq 'Class::MOP::Class'
208 my $meta = $self->$_;
209 !defined($meta) || $meta eq $base_metaclass{$_};
211 keys %base_metaclass;
213 for my $superclass (@superclasses) {
214 $self->_check_class_metaclass_compatibility($superclass);
217 for my $metaclass_type ( keys %base_metaclass ) {
218 next unless defined $self->$metaclass_type;
219 for my $superclass (@superclasses) {
220 $self->_check_single_metaclass_compatibility( $metaclass_type,
226 sub _check_class_metaclass_compatibility {
228 my ( $superclass_name ) = @_;
230 if (!$self->_class_metaclass_is_compatible($superclass_name)) {
231 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
233 my $super_meta_type = $super_meta->_real_ref_name;
235 confess "The metaclass of " . $self->name . " ("
236 . (ref($self)) . ")" . " is not compatible with "
237 . "the metaclass of its superclass, "
238 . $superclass_name . " (" . ($super_meta_type) . ")";
242 sub _class_metaclass_is_compatible {
244 my ( $superclass_name ) = @_;
246 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
249 my $super_meta_name = $super_meta->_real_ref_name;
251 return $self->_is_compatible_with($super_meta_name);
254 sub _check_single_metaclass_compatibility {
256 my ( $metaclass_type, $superclass_name ) = @_;
258 if (!$self->_single_metaclass_is_compatible($metaclass_type, $superclass_name)) {
259 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
260 my $metaclass_type_name = $metaclass_type;
261 $metaclass_type_name =~ s/_(?:meta)?class$//;
262 $metaclass_type_name =~ s/_/ /g;
263 confess "The $metaclass_type_name metaclass for "
264 . $self->name . " (" . ($self->$metaclass_type)
265 . ")" . " is not compatible with the "
266 . "$metaclass_type_name metaclass of its "
267 . "superclass, $superclass_name ("
268 . ($super_meta->$metaclass_type) . ")";
272 sub _single_metaclass_is_compatible {
274 my ( $metaclass_type, $superclass_name ) = @_;
276 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
279 # for instance, Moose::Meta::Class has a error_class attribute, but
280 # Class::MOP::Class doesn't - this shouldn't be an error
281 return 1 unless $super_meta->can($metaclass_type);
282 # for instance, Moose::Meta::Class has a destructor_class, but
283 # Class::MOP::Class doesn't - this shouldn't be an error
284 return 1 unless defined $super_meta->$metaclass_type;
285 # if metaclass is defined in superclass but not here, it's not compatible
286 # this is a really odd case
287 return 0 unless defined $self->$metaclass_type;
289 return $self->$metaclass_type->_is_compatible_with($super_meta->$metaclass_type);
292 sub _fix_metaclass_incompatibility {
294 my @supers = map { Class::MOP::Class->initialize($_) } @_;
297 for my $super (@supers) {
299 if $self->_can_fix_metaclass_incompatibility($super);
301 return unless $necessary;
303 for my $super (@supers) {
304 if (!$self->_class_metaclass_is_compatible($super->name)) {
305 $self->_fix_class_metaclass_incompatibility($super);
309 my %base_metaclass = $self->_base_metaclasses;
310 for my $metaclass_type (keys %base_metaclass) {
311 for my $super (@supers) {
312 if (!$self->_single_metaclass_is_compatible($metaclass_type, $super->name)) {
313 $self->_fix_single_metaclass_incompatibility(
314 $metaclass_type, $super
321 sub _can_fix_metaclass_incompatibility {
323 my ($super_meta) = @_;
325 return 1 if $self->_class_metaclass_can_be_made_compatible($super_meta);
327 my %base_metaclass = $self->_base_metaclasses;
328 for my $metaclass_type (keys %base_metaclass) {
329 return 1 if $self->_single_metaclass_can_be_made_compatible($super_meta, $metaclass_type);
335 sub _class_metaclass_can_be_made_compatible {
337 my ($super_meta) = @_;
339 return $self->_can_be_made_compatible_with($super_meta->_real_ref_name);
342 sub _single_metaclass_can_be_made_compatible {
344 my ($super_meta, $metaclass_type) = @_;
346 my $specific_meta = $self->$metaclass_type;
348 return unless $super_meta->can($metaclass_type);
349 my $super_specific_meta = $super_meta->$metaclass_type;
351 # for instance, Moose::Meta::Class has a destructor_class, but
352 # Class::MOP::Class doesn't - this shouldn't be an error
353 return unless defined $super_specific_meta;
355 # if metaclass is defined in superclass but not here, it's fixable
356 # this is a really odd case
357 return 1 unless defined $specific_meta;
359 return 1 if $specific_meta->_can_be_made_compatible_with($super_specific_meta);
362 sub _fix_class_metaclass_incompatibility {
364 my ( $super_meta ) = @_;
366 if ($self->_class_metaclass_can_be_made_compatible($super_meta)) {
368 || confess "Can't fix metaclass incompatibility for "
370 . " because it is not pristine.";
372 my $super_meta_name = $super_meta->_real_ref_name;
374 $self->_make_compatible_with($super_meta_name);
378 sub _fix_single_metaclass_incompatibility {
380 my ( $metaclass_type, $super_meta ) = @_;
382 if ($self->_single_metaclass_can_be_made_compatible($super_meta, $metaclass_type)) {
384 || confess "Can't fix metaclass incompatibility for "
386 . " because it is not pristine.";
388 my $new_metaclass = $self->$metaclass_type
389 ? $self->$metaclass_type->_get_compatible_metaclass($super_meta->$metaclass_type)
390 : $super_meta->$metaclass_type;
391 $self->{$metaclass_type} = $new_metaclass;
395 sub _restore_metaobjects_from {
399 $self->_restore_metamethods_from($old_meta);
400 $self->_restore_metaattributes_from($old_meta);
403 sub _remove_generated_metaobjects {
406 for my $attr (map { $self->get_attribute($_) } $self->get_attribute_list) {
407 $attr->remove_accessors;
411 # creating classes with MOP ...
417 unshift @args, 'package' if @args % 2 == 1;
420 (ref $options{superclasses} eq 'ARRAY')
421 || confess "You must pass an ARRAY ref of superclasses"
422 if exists $options{superclasses};
424 (ref $options{attributes} eq 'ARRAY')
425 || confess "You must pass an ARRAY ref of attributes"
426 if exists $options{attributes};
428 (ref $options{methods} eq 'HASH')
429 || confess "You must pass a HASH ref of methods"
430 if exists $options{methods};
432 my $package = delete $options{package};
433 my $superclasses = delete $options{superclasses};
434 my $attributes = delete $options{attributes};
435 my $methods = delete $options{methods};
436 my $meta_name = exists $options{meta_name}
437 ? delete $options{meta_name}
440 my $meta = $class->SUPER::create($package => %options);
442 $meta->_add_meta_method($meta_name)
443 if defined $meta_name;
445 $meta->superclasses(@{$superclasses})
446 if defined $superclasses;
448 # process attributes first, so that they can
449 # install accessors, but locally defined methods
450 # can then overwrite them. It is maybe a little odd, but
451 # I think this should be the order of things.
452 if (defined $attributes) {
453 foreach my $attr (@{$attributes}) {
454 $meta->add_attribute($attr);
457 if (defined $methods) {
458 foreach my $method_name (keys %{$methods}) {
459 $meta->add_method($method_name, $methods->{$method_name});
465 # XXX: something more intelligent here?
466 sub _anon_package_prefix { 'Class::MOP::Class::__ANON__::SERIAL::' }
468 sub create_anon_class { shift->create_anon(@_) }
469 sub is_anon_class { shift->is_anon(@_) }
471 sub _anon_cache_key {
474 # Makes something like Super::Class|Super::Class::2
476 join( '|', sort @{ $options{superclasses} || [] } ),
480 # Instance Construction & Cloning
486 # we need to protect the integrity of the
487 # Class::MOP::Class singletons here, so we
488 # delegate this to &construct_class_instance
489 # which will deal with the singletons
490 return $class->_construct_class_instance(@_)
491 if $class->name->isa('Class::MOP::Class');
492 return $class->_construct_instance(@_);
495 sub _construct_instance {
497 my $params = @_ == 1 ? $_[0] : {@_};
498 my $meta_instance = $class->get_meta_instance();
500 # the code below is almost certainly incorrect
501 # but this is foreign inheritance, so we might
502 # have to kludge it in the end.
504 if (my $instance_class = blessed($params->{__INSTANCE__})) {
505 ($instance_class eq $class->name)
506 || confess "Objects passed as the __INSTANCE__ parameter must "
507 . "already be blessed into the correct class, but "
508 . "$params->{__INSTANCE__} is not a " . $class->name;
509 $instance = $params->{__INSTANCE__};
511 elsif (exists $params->{__INSTANCE__}) {
512 confess "The __INSTANCE__ parameter must be a blessed reference, not "
513 . $params->{__INSTANCE__};
516 $instance = $meta_instance->create_instance();
518 foreach my $attr ($class->get_all_attributes()) {
519 $attr->initialize_instance_slot($meta_instance, $instance, $params);
521 if (Class::MOP::metaclass_is_weak($class->name)) {
522 $meta_instance->_set_mop_slot($instance, $class);
527 sub _inline_new_object {
531 'my $class = shift;',
532 '$class = Scalar::Util::blessed($class) || $class;',
533 $self->_inline_fallback_constructor('$class'),
534 $self->_inline_params('$params', '$class'),
535 $self->_inline_generate_instance('$instance', '$class'),
536 $self->_inline_slot_initializers,
537 $self->_inline_preserve_weak_metaclasses,
538 $self->_inline_extra_init,
543 sub _inline_fallback_constructor {
547 'return ' . $self->_generate_fallback_constructor($class),
548 'if ' . $class . ' ne \'' . $self->name . '\';',
552 sub _generate_fallback_constructor {
555 return 'Class::MOP::Class->initialize(' . $class . ')->new_object(@_)',
560 my ($params, $class) = @_;
562 'my ' . $params . ' = @_ == 1 ? $_[0] : {@_};',
566 sub _inline_generate_instance {
568 my ($inst, $class) = @_;
570 'my ' . $inst . ' = ' . $self->_inline_create_instance($class) . ';',
574 sub _inline_create_instance {
577 return $self->get_meta_instance->inline_create_instance(@_);
580 sub _inline_slot_initializers {
585 return map { $self->_inline_slot_initializer($_, $idx++) }
586 sort { $a->name cmp $b->name } $self->get_all_attributes;
589 sub _inline_slot_initializer {
591 my ($attr, $idx) = @_;
593 if (defined(my $init_arg = $attr->init_arg)) {
595 'if (exists $params->{\'' . $init_arg . '\'}) {',
596 $self->_inline_init_attr_from_constructor($attr, $idx),
599 if (my @default = $self->_inline_init_attr_from_default($attr, $idx)) {
608 elsif (my @default = $self->_inline_init_attr_from_default($attr, $idx)) {
620 sub _inline_init_attr_from_constructor {
622 my ($attr, $idx) = @_;
624 my @initial_value = $attr->_inline_set_value(
625 '$instance', '$params->{\'' . $attr->init_arg . '\'}',
628 push @initial_value, (
629 '$attrs->[' . $idx . ']->set_initial_value(',
631 $attr->_inline_instance_get('$instance'),
633 ) if $attr->has_initializer;
635 return @initial_value;
638 sub _inline_init_attr_from_default {
640 my ($attr, $idx) = @_;
642 my $default = $self->_inline_default_value($attr, $idx);
643 return unless $default;
645 my @initial_value = $attr->_inline_set_value('$instance', $default);
647 push @initial_value, (
648 '$attrs->[' . $idx . ']->set_initial_value(',
650 $attr->_inline_instance_get('$instance'),
652 ) if $attr->has_initializer;
654 return @initial_value;
657 sub _inline_default_value {
659 my ($attr, $index) = @_;
661 if ($attr->has_default) {
663 # default values can either be CODE refs
664 # in which case we need to call them. Or
665 # they can be scalars (strings/numbers)
666 # in which case we can just deal with them
667 # in the code we eval.
668 if ($attr->is_default_a_coderef) {
669 return '$defaults->[' . $index . ']->($instance)';
672 return '$defaults->[' . $index . ']';
675 elsif ($attr->has_builder) {
676 return '$instance->' . $attr->builder;
683 sub _inline_preserve_weak_metaclasses {
685 if (Class::MOP::metaclass_is_weak($self->name)) {
687 $self->_inline_set_mop_slot(
688 '$instance', 'Class::MOP::class_of($class)'
697 sub _inline_extra_init { }
699 sub _eval_environment {
702 my @attrs = sort { $a->name cmp $b->name } $self->get_all_attributes;
704 my $defaults = [map { $_->default } @attrs];
707 '$defaults' => \$defaults,
712 sub get_meta_instance {
714 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
717 sub _create_meta_instance {
720 my $instance = $self->instance_metaclass->new(
721 associated_metaclass => $self,
722 attributes => [ $self->get_all_attributes() ],
725 $self->add_meta_instance_dependencies()
726 if $instance->is_dependent_on_superclasses();
731 # TODO: this is actually not being used!
732 sub _inline_rebless_instance {
735 return $self->get_meta_instance->inline_rebless_instance_structure(@_);
738 sub _inline_get_mop_slot {
741 return $self->get_meta_instance->_inline_get_mop_slot(@_);
744 sub _inline_set_mop_slot {
747 return $self->get_meta_instance->_inline_set_mop_slot(@_);
750 sub _inline_clear_mop_slot {
753 return $self->get_meta_instance->_inline_clear_mop_slot(@_);
758 my $instance = shift;
759 (blessed($instance) && $instance->isa($class->name))
760 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
763 # we need to protect the integrity of the
764 # Class::MOP::Class singletons here, they
765 # should not be cloned.
766 return $instance if $instance->isa('Class::MOP::Class');
767 $class->_clone_instance($instance, @_);
770 sub _clone_instance {
771 my ($class, $instance, %params) = @_;
773 || confess "You can only clone instances, ($instance) is not a blessed instance";
774 my $meta_instance = $class->get_meta_instance();
775 my $clone = $meta_instance->clone_instance($instance);
776 foreach my $attr ($class->get_all_attributes()) {
777 if ( defined( my $init_arg = $attr->init_arg ) ) {
778 if (exists $params{$init_arg}) {
779 $attr->set_value($clone, $params{$init_arg});
786 sub _force_rebless_instance {
787 my ($self, $instance, %params) = @_;
788 my $old_metaclass = Class::MOP::class_of($instance);
790 $old_metaclass->rebless_instance_away($instance, $self, %params)
793 my $meta_instance = $self->get_meta_instance;
795 if (Class::MOP::metaclass_is_weak($old_metaclass->name)) {
796 $meta_instance->_clear_mop_slot($instance);
800 # we use $_[1] here because of t/cmop/rebless_overload.t regressions
802 $meta_instance->rebless_instance_structure($_[1], $self);
804 $self->_fixup_attributes_after_rebless($instance, $old_metaclass, %params);
806 if (Class::MOP::metaclass_is_weak($self->name)) {
807 $meta_instance->_set_mop_slot($instance, $self);
811 sub rebless_instance {
812 my ($self, $instance, %params) = @_;
813 my $old_metaclass = Class::MOP::class_of($instance);
815 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
816 $self->name->isa($old_class)
817 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
819 $self->_force_rebless_instance($_[1], %params);
824 sub rebless_instance_back {
825 my ( $self, $instance ) = @_;
826 my $old_metaclass = Class::MOP::class_of($instance);
829 = $old_metaclass ? $old_metaclass->name : blessed($instance);
830 $old_class->isa( $self->name )
832 "You may rebless only into a superclass of ($old_class), of which ("
836 $self->_force_rebless_instance($_[1]);
841 sub rebless_instance_away {
842 # this intentionally does nothing, it is just a hook
845 sub _fixup_attributes_after_rebless {
847 my ($instance, $rebless_from, %params) = @_;
848 my $meta_instance = $self->get_meta_instance;
850 for my $attr ( $rebless_from->get_all_attributes ) {
851 next if $self->find_attribute_by_name( $attr->name );
852 $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
855 foreach my $attr ( $self->get_all_attributes ) {
856 if ( $attr->has_value($instance) ) {
857 if ( defined( my $init_arg = $attr->init_arg ) ) {
858 $params{$init_arg} = $attr->get_value($instance)
859 unless exists $params{$init_arg};
862 $attr->set_value($instance, $attr->get_value($instance));
867 foreach my $attr ($self->get_all_attributes) {
868 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
872 sub _attach_attribute {
873 my ($self, $attribute) = @_;
874 $attribute->attach_to_class($self);
877 sub _post_add_attribute {
878 my ( $self, $attribute ) = @_;
880 $self->invalidate_meta_instances;
882 # invalidate package flag here
885 $attribute->install_accessors;
888 $self->remove_attribute( $attribute->name );
893 sub remove_attribute {
896 my $removed_attribute = $self->SUPER::remove_attribute(@_)
899 $self->invalidate_meta_instances;
901 $removed_attribute->remove_accessors;
902 $removed_attribute->detach_from_class;
904 return$removed_attribute;
907 sub find_attribute_by_name {
908 my ( $self, $attr_name ) = @_;
910 foreach my $class ( $self->linearized_isa ) {
911 # fetch the meta-class ...
912 my $meta = Class::MOP::Class->initialize($class);
913 return $meta->get_attribute($attr_name)
914 if $meta->has_attribute($attr_name);
920 sub get_all_attributes {
922 my %attrs = map { %{ Class::MOP::Class->initialize($_)->_attribute_map } }
923 reverse $self->linearized_isa;
924 return values %attrs;
932 my $isa = $self->get_or_add_package_symbol('@ISA');
939 # on 5.8 and below, we need to call
940 # a method to get Perl to detect
941 # a cycle in the class hierarchy
942 my $class = $self->name;
946 # we need to check the metaclass
947 # compatibility here so that we can
948 # be sure that the superclass is
949 # not potentially creating an issues
950 # we don't know about
952 $self->_check_metaclass_compatibility();
953 $self->_superclasses_updated();
959 sub _superclasses_updated {
961 $self->update_meta_instance_dependencies();
962 # keep strong references to all our parents, so they don't disappear if
963 # they are anon classes and don't have any direct instances
964 $self->_superclass_metas(
965 map { Class::MOP::class_of($_) } $self->superclasses
969 sub _superclass_metas {
971 $self->{_superclass_metas} = [@_];
976 my $super_class = $self->name;
978 return @{ $super_class->mro::get_isarev() };
981 sub direct_subclasses {
983 my $super_class = $self->name;
988 } Class::MOP::Class->initialize($_)->superclasses
993 return @{ mro::get_linear_isa( (shift)->name ) };
996 sub class_precedence_list {
998 my $name = $self->name;
1000 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
1002 # We need to check for circular inheritance here
1003 # if we are are not on 5.10, cause 5.8 detects it
1004 # late. This will do nothing if all is well, and
1005 # blow up otherwise. Yes, it's an ugly hack, better
1006 # suggestions are welcome.
1008 ($name || return)->isa('This is a test for circular inheritance')
1011 # if our mro is c3, we can
1012 # just grab the linear_isa
1013 if (mro::get_mro($name) eq 'c3') {
1014 return @{ mro::get_linear_isa($name) }
1018 # we can't grab the linear_isa for dfs
1019 # since it has all the duplicates
1024 Class::MOP::Class->initialize($_)->class_precedence_list()
1025 } $self->superclasses()
1033 my $fetch_and_prepare_method = sub {
1034 my ($self, $method_name) = @_;
1035 my $wrapped_metaclass = $self->wrapped_method_metaclass;
1037 my $method = $self->get_method($method_name);
1038 # if we dont have local ...
1040 # try to find the next method
1041 $method = $self->find_next_method_by_name($method_name);
1042 # die if it does not exist
1044 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
1045 # and now make sure to wrap it
1046 # even if it is already wrapped
1047 # because we need a new sub ref
1048 $method = $wrapped_metaclass->wrap($method,
1049 package_name => $self->name,
1050 name => $method_name,
1054 # now make sure we wrap it properly
1055 $method = $wrapped_metaclass->wrap($method,
1056 package_name => $self->name,
1057 name => $method_name,
1058 ) unless $method->isa($wrapped_metaclass);
1060 $self->add_method($method_name => $method);
1064 sub add_before_method_modifier {
1065 my ($self, $method_name, $method_modifier) = @_;
1066 (defined $method_name && length $method_name)
1067 || confess "You must pass in a method name";
1068 my $method = $fetch_and_prepare_method->($self, $method_name);
1069 $method->add_before_modifier(
1070 subname(':before' => $method_modifier)
1074 sub add_after_method_modifier {
1075 my ($self, $method_name, $method_modifier) = @_;
1076 (defined $method_name && length $method_name)
1077 || confess "You must pass in a method name";
1078 my $method = $fetch_and_prepare_method->($self, $method_name);
1079 $method->add_after_modifier(
1080 subname(':after' => $method_modifier)
1084 sub add_around_method_modifier {
1085 my ($self, $method_name, $method_modifier) = @_;
1086 (defined $method_name && length $method_name)
1087 || confess "You must pass in a method name";
1088 my $method = $fetch_and_prepare_method->($self, $method_name);
1089 $method->add_around_modifier(
1090 subname(':around' => $method_modifier)
1095 # the methods above used to be named like this:
1096 # ${pkg}::${method}:(before|after|around)
1097 # but this proved problematic when using one modifier
1098 # to wrap multiple methods (something which is likely
1099 # to happen pretty regularly IMO). So instead of naming
1100 # it like this, I have chosen to just name them purely
1101 # with their modifier names, like so:
1102 # :(before|after|around)
1103 # The fact is that in a stack trace, it will be fairly
1104 # evident from the context what method they are attached
1105 # to, and so don't need the fully qualified name.
1108 sub find_method_by_name {
1109 my ($self, $method_name) = @_;
1110 (defined $method_name && length $method_name)
1111 || confess "You must define a method name to find";
1112 foreach my $class ($self->linearized_isa) {
1113 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1114 return $method if defined $method;
1119 sub get_all_methods {
1123 for my $class ( reverse $self->linearized_isa ) {
1124 my $meta = Class::MOP::Class->initialize($class);
1126 $methods{ $_->name } = $_ for $meta->_get_local_methods;
1129 return values %methods;
1132 sub get_all_method_names {
1135 return grep { !$uniq{$_}++ } map { Class::MOP::Class->initialize($_)->get_method_list } $self->linearized_isa;
1138 sub find_all_methods_by_name {
1139 my ($self, $method_name) = @_;
1140 (defined $method_name && length $method_name)
1141 || confess "You must define a method name to find";
1143 foreach my $class ($self->linearized_isa) {
1144 # fetch the meta-class ...
1145 my $meta = Class::MOP::Class->initialize($class);
1147 name => $method_name,
1149 code => $meta->get_method($method_name)
1150 } if $meta->has_method($method_name);
1155 sub find_next_method_by_name {
1156 my ($self, $method_name) = @_;
1157 (defined $method_name && length $method_name)
1158 || confess "You must define a method name to find";
1159 my @cpl = $self->linearized_isa;
1160 shift @cpl; # discard ourselves
1161 foreach my $class (@cpl) {
1162 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1163 return $method if defined $method;
1168 sub update_meta_instance_dependencies {
1171 if ( $self->{meta_instance_dependencies} ) {
1172 return $self->add_meta_instance_dependencies;
1176 sub add_meta_instance_dependencies {
1179 $self->remove_meta_instance_dependencies;
1181 my @attrs = $self->get_all_attributes();
1184 my @classes = grep { not $seen{ $_->name }++ }
1185 map { $_->associated_class } @attrs;
1187 foreach my $class (@classes) {
1188 $class->add_dependent_meta_instance($self);
1191 $self->{meta_instance_dependencies} = \@classes;
1194 sub remove_meta_instance_dependencies {
1197 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
1198 foreach my $class (@$classes) {
1199 $class->remove_dependent_meta_instance($self);
1209 sub add_dependent_meta_instance {
1210 my ( $self, $metaclass ) = @_;
1211 push @{ $self->{dependent_meta_instances} }, $metaclass;
1214 sub remove_dependent_meta_instance {
1215 my ( $self, $metaclass ) = @_;
1216 my $name = $metaclass->name;
1217 @$_ = grep { $_->name ne $name } @$_
1218 for $self->{dependent_meta_instances};
1221 sub invalidate_meta_instances {
1223 $_->invalidate_meta_instance()
1224 for $self, @{ $self->{dependent_meta_instances} };
1227 sub invalidate_meta_instance {
1229 undef $self->{_meta_instance};
1232 # check if we can reinitialize
1236 # if any local attr is defined
1237 return if $self->get_attribute_list;
1239 # or any non-declared methods
1240 for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1241 return if $method->isa("Class::MOP::Method::Generated");
1242 # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1250 sub is_mutable { 1 }
1251 sub is_immutable { 0 }
1253 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1255 sub _immutable_options {
1256 my ( $self, @args ) = @_;
1259 inline_accessors => 1,
1260 inline_constructor => 1,
1261 inline_destructor => 0,
1263 immutable_trait => $self->immutable_trait,
1264 constructor_name => $self->constructor_name,
1265 constructor_class => $self->constructor_class,
1266 destructor_class => $self->destructor_class,
1271 sub make_immutable {
1272 my ( $self, @args ) = @_;
1274 return unless $self->is_mutable;
1276 my ($file, $line) = (caller)[1..2];
1278 $self->_initialize_immutable(
1281 $self->_immutable_options(@args),
1283 $self->_rebless_as_immutable(@args);
1291 if ( $self->is_immutable ) {
1292 my @args = $self->immutable_options;
1293 $self->_rebless_as_mutable();
1294 $self->_remove_inlined_code(@args);
1295 delete $self->{__immutable};
1303 sub _rebless_as_immutable {
1304 my ( $self, @args ) = @_;
1306 $self->{__immutable}{original_class} = ref $self;
1308 bless $self => $self->_immutable_metaclass(@args);
1311 sub _immutable_metaclass {
1312 my ( $self, %args ) = @_;
1314 if ( my $class = $args{immutable_metaclass} ) {
1318 my $trait = $args{immutable_trait} = $self->immutable_trait
1319 || confess "no immutable trait specified for $self";
1321 my $meta = $self->meta;
1322 my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1326 if ( $meta_attr and $trait eq $meta_attr->default ) {
1327 # if the trait is the same as the default we try and pick a
1328 # predictable name for the immutable metaclass
1329 $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1332 $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1333 $trait, 'ForMetaClass', ref($self);
1337 if is_class_loaded($class_name);
1339 # If the metaclass is a subclass of CMOP::Class which has had
1340 # metaclass roles applied (via Moose), then we want to make sure
1341 # that we preserve that anonymous class (see Fey::ORM for an
1342 # example of where this matters).
1343 my $meta_name = $meta->_real_ref_name;
1345 my $immutable_meta = $meta_name->create(
1347 superclasses => [ ref $self ],
1350 Class::MOP::MiniTrait::apply( $immutable_meta, $trait );
1352 $immutable_meta->make_immutable(
1353 inline_constructor => 0,
1354 inline_accessors => 0,
1360 sub _remove_inlined_code {
1363 $self->remove_method( $_->name ) for $self->_inlined_methods;
1365 delete $self->{__immutable}{inlined_methods};
1368 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1370 sub _add_inlined_method {
1371 my ( $self, $method ) = @_;
1373 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1376 sub _initialize_immutable {
1377 my ( $self, %args ) = @_;
1379 $self->{__immutable}{options} = \%args;
1380 $self->_install_inlined_code(%args);
1383 sub _install_inlined_code {
1384 my ( $self, %args ) = @_;
1387 $self->_inline_accessors(%args) if $args{inline_accessors};
1388 $self->_inline_constructor(%args) if $args{inline_constructor};
1389 $self->_inline_destructor(%args) if $args{inline_destructor};
1392 sub _rebless_as_mutable {
1395 bless $self, $self->_get_mutable_metaclass_name;
1400 sub _inline_accessors {
1403 foreach my $attr_name ( $self->get_attribute_list ) {
1404 $self->get_attribute($attr_name)->install_accessors(1);
1408 sub _inline_constructor {
1409 my ( $self, %args ) = @_;
1411 my $name = $args{constructor_name};
1412 # A class may not even have a constructor, and that's okay.
1413 return unless defined $name;
1415 if ( $self->has_method($name) && !$args{replace_constructor} ) {
1416 my $class = $self->name;
1417 warn "Not inlining a constructor for $class since it defines"
1418 . " its own constructor.\n"
1419 . "If you are certain you don't need to inline your"
1420 . " constructor, specify inline_constructor => 0 in your"
1421 . " call to $class->meta->make_immutable\n";
1425 my $constructor_class = $args{constructor_class};
1427 load_class($constructor_class);
1429 my $constructor = $constructor_class->new(
1433 package_name => $self->name,
1435 definition_context => {
1436 description => "constructor " . $self->name . "::" . $name,
1437 file => $args{file},
1438 line => $args{line},
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 load_class($destructor_class);
1466 return unless $destructor_class->is_needed($self);
1468 my $destructor = $destructor_class->new(
1471 package_name => $self->name,
1473 definition_context => {
1474 description => "destructor " . $self->name . "::DESTROY",
1475 file => $args{file},
1476 line => $args{line},
1480 if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1481 $self->add_method( 'DESTROY' => $destructor );
1482 $self->_add_inlined_method($destructor);
1488 # ABSTRACT: Class Meta Object
1496 # assuming that class Foo
1497 # has been defined, you can
1499 # use this for introspection ...
1501 # add a method to Foo ...
1502 Foo->meta->add_method( 'bar' => sub {...} )
1504 # get a list of all the classes searched
1505 # the method dispatcher in the correct order
1506 Foo->meta->class_precedence_list()
1508 # remove a method from Foo
1509 Foo->meta->remove_method('bar');
1511 # or use this to actually create classes ...
1513 Class::MOP::Class->create(
1516 superclasses => ['Foo'],
1518 Class::MOP::Attribute->new('$bar'),
1519 Class::MOP::Attribute->new('$baz'),
1522 calculate_bar => sub {...},
1523 construct_baz => sub {...}
1530 The Class Protocol is the largest and most complex part of the
1531 Class::MOP meta-object protocol. It controls the introspection and
1532 manipulation of Perl 5 classes, and it can create them as well. The
1533 best way to understand what this module can do is to read the
1534 documentation for each of its methods.
1538 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1542 =head2 Class construction
1544 These methods all create new C<Class::MOP::Class> objects. These
1545 objects can represent existing classes or they can be used to create
1546 new classes from scratch.
1548 The metaclass object for a given class is a singleton. If you attempt
1549 to create a metaclass for the same class twice, you will just get the
1554 =item B<< Class::MOP::Class->create($package_name, %options) >>
1556 This method creates a new C<Class::MOP::Class> object with the given
1557 package name. It accepts a number of options:
1563 An optional version number for the newly created package.
1567 An optional authority for the newly created package.
1569 =item * superclasses
1571 An optional array reference of superclass names.
1575 An optional hash reference of methods for the class. The keys of the
1576 hash reference are method names and values are subroutine references.
1580 An optional array reference of L<Class::MOP::Attribute> objects.
1584 Specifies the name to install the C<meta> method for this class under.
1585 If it is not passed, C<meta> is assumed, and if C<undef> is explicitly
1586 given, no meta method will be installed.
1590 If true, the metaclass that is stored in the global cache will be a
1593 Classes created in this way are destroyed once the metaclass they are
1594 attached to goes out of scope, and will be removed from Perl's internal
1597 All instances of a class with a weakened metaclass keep a special
1598 reference to the metaclass object, which prevents the metaclass from
1599 going out of scope while any instances exist.
1601 This only works if the instance is based on a hash reference, however.
1605 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1607 This method works just like C<< Class::MOP::Class->create >> but it
1608 creates an "anonymous" class. In fact, the class does have a name, but
1609 that name is a unique name generated internally by this module.
1611 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1612 parameters that C<create> accepts.
1614 Anonymous classes default to C<< weaken => 1 >>, although this can be
1617 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1619 This method will initialize a C<Class::MOP::Class> object for the
1620 named package. Unlike C<create>, this method I<will not> create a new
1623 The purpose of this method is to retrieve a C<Class::MOP::Class>
1624 object for introspecting an existing class.
1626 If an existing C<Class::MOP::Class> object exists for the named
1627 package, it will be returned, and any options provided will be
1630 If the object does not yet exist, it will be created.
1632 The valid options that can be passed to this method are
1633 C<attribute_metaclass>, C<method_metaclass>,
1634 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1635 optional, and default to the appropriate class in the C<Class::MOP>
1640 =head2 Object instance construction and cloning
1642 These methods are all related to creating and/or cloning object
1647 =item B<< $metaclass->clone_object($instance, %params) >>
1649 This method clones an existing object instance. Any parameters you
1650 provide are will override existing attribute values in the object.
1652 This is a convenience method for cloning an object instance, then
1653 blessing it into the appropriate package.
1655 You could implement a clone method in your class, using this method:
1658 my ($self, %params) = @_;
1659 $self->meta->clone_object($self, %params);
1662 =item B<< $metaclass->rebless_instance($instance, %params) >>
1664 This method changes the class of C<$instance> to the metaclass's class.
1666 You can only rebless an instance into a subclass of its current
1667 class. If you pass any additional parameters, these will be treated
1668 like constructor parameters and used to initialize the object's
1669 attributes. Any existing attributes that are already set will be
1672 Before reblessing the instance, this method will call
1673 C<rebless_instance_away> on the instance's current metaclass. This method
1674 will be passed the instance, the new metaclass, and any parameters
1675 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1676 does nothing; it is merely a hook.
1678 =item B<< $metaclass->rebless_instance_back($instance) >>
1680 Does the same thing as C<rebless_instance>, except that you can only
1681 rebless an instance into one of its superclasses. Any attributes that
1682 do not exist in the superclass will be deinitialized.
1684 This is a much more dangerous operation than C<rebless_instance>,
1685 especially when multiple inheritance is involved, so use this carefully!
1687 =item B<< $metaclass->new_object(%params) >>
1689 This method is used to create a new object of the metaclass's
1690 class. Any parameters you provide are used to initialize the
1691 instance's attributes. A special C<__INSTANCE__> key can be passed to
1692 provide an already generated instance, rather than having Class::MOP
1693 generate it for you. This is mostly useful for using Class::MOP with
1694 foreign classes which generate instances using their own constructors.
1696 =item B<< $metaclass->instance_metaclass >>
1698 Returns the class name of the instance metaclass. See
1699 L<Class::MOP::Instance> for more information on the instance
1702 =item B<< $metaclass->get_meta_instance >>
1704 Returns an instance of the C<instance_metaclass> to be used in the
1705 construction of a new instance of the class.
1709 =head2 Informational predicates
1711 These are a few predicate methods for asking information about the
1716 =item B<< $metaclass->is_anon_class >>
1718 This returns true if the class was created by calling C<<
1719 Class::MOP::Class->create_anon_class >>.
1721 =item B<< $metaclass->is_mutable >>
1723 This returns true if the class is still mutable.
1725 =item B<< $metaclass->is_immutable >>
1727 This returns true if the class has been made immutable.
1729 =item B<< $metaclass->is_pristine >>
1731 A class is I<not> pristine if it has non-inherited attributes or if it
1732 has any generated methods.
1736 =head2 Inheritance Relationships
1740 =item B<< $metaclass->superclasses(@superclasses) >>
1742 This is a read-write accessor which represents the superclass
1743 relationships of the metaclass's class.
1745 This is basically sugar around getting and setting C<@ISA>.
1747 =item B<< $metaclass->class_precedence_list >>
1749 This returns a list of all of the class's ancestor classes. The
1750 classes are returned in method dispatch order.
1752 =item B<< $metaclass->linearized_isa >>
1754 This returns a list based on C<class_precedence_list> but with all
1757 =item B<< $metaclass->subclasses >>
1759 This returns a list of all subclasses for this class, even indirect
1762 =item B<< $metaclass->direct_subclasses >>
1764 This returns a list of immediate subclasses for this class, which does not
1765 include indirect subclasses.
1769 =head2 Method introspection and creation
1771 These methods allow you to introspect a class's methods, as well as
1772 add, remove, or change methods.
1774 Determining what is truly a method in a Perl 5 class requires some
1775 heuristics (aka guessing).
1777 Methods defined outside the package with a fully qualified name (C<sub
1778 Package::name { ... }>) will be included. Similarly, methods named
1779 with a fully qualified name using L<Sub::Name> are also included.
1781 However, we attempt to ignore imported functions.
1783 Ultimately, we are using heuristics to determine what truly is a
1784 method in a class, and these heuristics may get the wrong answer in
1785 some edge cases. However, for most "normal" cases the heuristics work
1790 =item B<< $metaclass->get_method($method_name) >>
1792 This will return a L<Class::MOP::Method> for the specified
1793 C<$method_name>. If the class does not have the specified method, it
1796 =item B<< $metaclass->has_method($method_name) >>
1798 Returns a boolean indicating whether or not the class defines the
1799 named method. It does not include methods inherited from parent
1802 =item B<< $metaclass->get_method_list >>
1804 This will return a list of method I<names> for all methods defined in
1807 =item B<< $metaclass->add_method($method_name, $method) >>
1809 This method takes a method name and a subroutine reference, and adds
1810 the method to the class.
1812 The subroutine reference can be a L<Class::MOP::Method>, and you are
1813 strongly encouraged to pass a meta method object instead of a code
1814 reference. If you do so, that object gets stored as part of the
1815 class's method map directly. If not, the meta information will have to
1816 be recreated later, and may be incorrect.
1818 If you provide a method object, this method will clone that object if
1819 the object's package name does not match the class name. This lets us
1820 track the original source of any methods added from other classes
1821 (notably Moose roles).
1823 =item B<< $metaclass->remove_method($method_name) >>
1825 Remove the named method from the class. This method returns the
1826 L<Class::MOP::Method> object for the method.
1828 =item B<< $metaclass->method_metaclass >>
1830 Returns the class name of the method metaclass, see
1831 L<Class::MOP::Method> for more information on the method metaclass.
1833 =item B<< $metaclass->wrapped_method_metaclass >>
1835 Returns the class name of the wrapped method metaclass, see
1836 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1839 =item B<< $metaclass->get_all_methods >>
1841 This will traverse the inheritance hierarchy and return a list of all
1842 the L<Class::MOP::Method> objects for this class and its parents.
1844 =item B<< $metaclass->find_method_by_name($method_name) >>
1846 This will return a L<Class::MOP::Method> for the specified
1847 C<$method_name>. If the class does not have the specified method, it
1850 Unlike C<get_method>, this method I<will> look for the named method in
1853 =item B<< $metaclass->get_all_method_names >>
1855 This will return a list of method I<names> for all of this class's
1856 methods, including inherited methods.
1858 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1860 This method looks for the named method in the class and all of its
1861 parents. It returns every matching method it finds in the inheritance
1862 tree, so it returns a list of methods.
1864 Each method is returned as a hash reference with three keys. The keys
1865 are C<name>, C<class>, and C<code>. The C<code> key has a
1866 L<Class::MOP::Method> object as its value.
1868 The list of methods is distinct.
1870 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1872 This method returns the first method in any superclass matching the
1873 given name. It is effectively the method that C<SUPER::$method_name>
1878 =head2 Attribute introspection and creation
1880 Because Perl 5 does not have a core concept of attributes in classes,
1881 we can only return information about attributes which have been added
1882 via this class's methods. We cannot discover information about
1883 attributes which are defined in terms of "regular" Perl 5 methods.
1887 =item B<< $metaclass->get_attribute($attribute_name) >>
1889 This will return a L<Class::MOP::Attribute> for the specified
1890 C<$attribute_name>. If the class does not have the specified
1891 attribute, it returns C<undef>.
1893 NOTE that get_attribute does not search superclasses, for that you
1894 need to use C<find_attribute_by_name>.
1896 =item B<< $metaclass->has_attribute($attribute_name) >>
1898 Returns a boolean indicating whether or not the class defines the
1899 named attribute. It does not include attributes inherited from parent
1902 =item B<< $metaclass->get_attribute_list >>
1904 This will return a list of attributes I<names> for all attributes
1905 defined in this class. Note that this operates on the current class
1906 only, it does not traverse the inheritance hierarchy.
1908 =item B<< $metaclass->get_all_attributes >>
1910 This will traverse the inheritance hierarchy and return a list of all
1911 the L<Class::MOP::Attribute> objects for this class and its parents.
1913 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1915 This will return a L<Class::MOP::Attribute> for the specified
1916 C<$attribute_name>. If the class does not have the specified
1917 attribute, it returns C<undef>.
1919 Unlike C<get_attribute>, this attribute I<will> look for the named
1920 attribute in superclasses.
1922 =item B<< $metaclass->add_attribute(...) >>
1924 This method accepts either an existing L<Class::MOP::Attribute>
1925 object or parameters suitable for passing to that class's C<new>
1928 The attribute provided will be added to the class.
1930 Any accessor methods defined by the attribute will be added to the
1931 class when the attribute is added.
1933 If an attribute of the same name already exists, the old attribute
1934 will be removed first.
1936 =item B<< $metaclass->remove_attribute($attribute_name) >>
1938 This will remove the named attribute from the class, and
1939 L<Class::MOP::Attribute> object.
1941 Removing an attribute also removes any accessor methods defined by the
1944 However, note that removing an attribute will only affect I<future>
1945 object instances created for this class, not existing instances.
1947 =item B<< $metaclass->attribute_metaclass >>
1949 Returns the class name of the attribute metaclass for this class. By
1950 default, this is L<Class::MOP::Attribute>.
1954 =head2 Class Immutability
1956 Making a class immutable "freezes" the class definition. You can no
1957 longer call methods which alter the class, such as adding or removing
1958 methods or attributes.
1960 Making a class immutable lets us optimize the class by inlining some
1961 methods, and also allows us to optimize some methods on the metaclass
1964 After immutabilization, the metaclass object will cache most informational
1965 methods that returns information about methods or attributes. Methods which
1966 would alter the class, such as C<add_attribute> and C<add_method>, will
1967 throw an error on an immutable metaclass object.
1969 The immutabilization system in L<Moose> takes much greater advantage
1970 of the inlining features than Class::MOP itself does.
1974 =item B<< $metaclass->make_immutable(%options) >>
1976 This method will create an immutable transformer and use it to make
1977 the class and its metaclass object immutable.
1979 This method accepts the following options:
1983 =item * inline_accessors
1985 =item * inline_constructor
1987 =item * inline_destructor
1989 These are all booleans indicating whether the specified method(s)
1992 By default, accessors and the constructor are inlined, but not the
1995 =item * immutable_trait
1997 The name of a class which will be used as a parent class for the
1998 metaclass object being made immutable. This "trait" implements the
1999 post-immutability functionality of the metaclass (but not the
2000 transformation itself).
2002 This defaults to L<Class::MOP::Class::Immutable::Trait>.
2004 =item * constructor_name
2006 This is the constructor method name. This defaults to "new".
2008 =item * constructor_class
2010 The name of the method metaclass for constructors. It will be used to
2011 generate the inlined constructor. This defaults to
2012 "Class::MOP::Method::Constructor".
2014 =item * replace_constructor
2016 This is a boolean indicating whether an existing constructor should be
2017 replaced when inlining a constructor. This defaults to false.
2019 =item * destructor_class
2021 The name of the method metaclass for destructors. It will be used to
2022 generate the inlined destructor. This defaults to
2023 "Class::MOP::Method::Denstructor".
2025 =item * replace_destructor
2027 This is a boolean indicating whether an existing destructor should be
2028 replaced when inlining a destructor. This defaults to false.
2032 =item B<< $metaclass->immutable_options >>
2034 Returns a hash of the options used when making the class immutable, including
2035 both defaults and anything supplied by the user in the call to C<<
2036 $metaclass->make_immutable >>. This is useful if you need to temporarily make
2037 a class mutable and then restore immutability as it was before.
2039 =item B<< $metaclass->make_mutable >>
2041 Calling this method reverse the immutabilization transformation.
2045 =head2 Method Modifiers
2047 Method modifiers are hooks which allow a method to be wrapped with
2048 I<before>, I<after> and I<around> method modifiers. Every time a
2049 method is called, its modifiers are also called.
2051 A class can modify its own methods, as well as methods defined in
2054 =head3 How method modifiers work?
2056 Method modifiers work by wrapping the original method and then
2057 replacing it in the class's symbol table. The wrappers will handle
2058 calling all the modifiers in the appropriate order and preserving the
2059 calling context for the original method.
2061 The return values of C<before> and C<after> modifiers are
2062 ignored. This is because their purpose is B<not> to filter the input
2063 and output of the primary method (this is done with an I<around>
2066 This may seem like an odd restriction to some, but doing this allows
2067 for simple code to be added at the beginning or end of a method call
2068 without altering the function of the wrapped method or placing any
2069 extra responsibility on the code of the modifier.
2071 Of course if you have more complex needs, you can use the C<around>
2072 modifier which allows you to change both the parameters passed to the
2073 wrapped method, as well as its return value.
2075 Before and around modifiers are called in last-defined-first-called
2076 order, while after modifiers are called in first-defined-first-called
2077 order. So the call tree might looks something like this:
2089 =head3 What is the performance impact?
2091 Of course there is a performance cost associated with method
2092 modifiers, but we have made every effort to make that cost directly
2093 proportional to the number of modifier features you use.
2095 The wrapping method does its best to B<only> do as much work as it
2096 absolutely needs to. In order to do this we have moved some of the
2097 performance costs to set-up time, where they are easier to amortize.
2099 All this said, our benchmarks have indicated the following:
2101 simple wrapper with no modifiers 100% slower
2102 simple wrapper with simple before modifier 400% slower
2103 simple wrapper with simple after modifier 450% slower
2104 simple wrapper with simple around modifier 500-550% slower
2105 simple wrapper with all 3 modifiers 1100% slower
2107 These numbers may seem daunting, but you must remember, every feature
2108 comes with some cost. To put things in perspective, just doing a
2109 simple C<AUTOLOAD> which does nothing but extract the name of the
2110 method called and return it costs about 400% over a normal method
2115 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
2117 This wraps the specified method with the supplied subroutine
2118 reference. The modifier will be called as a method itself, and will
2119 receive the same arguments as are passed to the method.
2121 When the modifier exits, the wrapped method will be called.
2123 The return value of the modifier will be ignored.
2125 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
2127 This wraps the specified method with the supplied subroutine
2128 reference. The modifier will be called as a method itself, and will
2129 receive the same arguments as are passed to the method.
2131 When the wrapped methods exits, the modifier will be called.
2133 The return value of the modifier will be ignored.
2135 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
2137 This wraps the specified method with the supplied subroutine
2140 The first argument passed to the modifier will be a subroutine
2141 reference to the wrapped method. The second argument is the object,
2142 and after that come any arguments passed when the method is called.
2144 The around modifier can choose to call the original method, as well as
2145 what arguments to pass if it does so.
2147 The return value of the modifier is what will be seen by the caller.
2151 =head2 Introspection
2155 =item B<< Class::MOP::Class->meta >>
2157 This will return a L<Class::MOP::Class> instance for this class.
2159 It should also be noted that L<Class::MOP> will actually bootstrap
2160 this module by installing a number of attribute meta-objects into its