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';
17 use List::MoreUtils 'all';
19 use base 'Class::MOP::Module',
20 'Class::MOP::Mixin::HasAttributes',
21 'Class::MOP::Mixin::HasMethods';
31 $package_name = shift;
34 $package_name = $options{package};
37 ($package_name && !ref($package_name))
38 || confess "You must pass a package name and it cannot be blessed";
40 return Class::MOP::get_metaclass_by_name($package_name)
41 || $class->_construct_class_instance(package => $package_name, @_);
45 my ( $class, @args ) = @_;
46 unshift @args, "package" if @args % 2;
48 my $old_metaclass = blessed($options{package})
50 : Class::MOP::get_metaclass_by_name($options{package});
51 $options{weaken} = Class::MOP::metaclass_is_weak($old_metaclass->name)
52 if !exists $options{weaken}
53 && blessed($old_metaclass)
54 && $old_metaclass->isa('Class::MOP::Class');
55 $old_metaclass->_remove_generated_metaobjects
56 if $old_metaclass && $old_metaclass->isa('Class::MOP::Class');
57 my $new_metaclass = $class->SUPER::reinitialize(%options);
58 $new_metaclass->_restore_metaobjects_from($old_metaclass)
59 if $old_metaclass && $old_metaclass->isa('Class::MOP::Class');
60 return $new_metaclass;
63 # NOTE: (meta-circularity)
64 # this is a special form of _construct_instance
65 # (see below), which is used to construct class
66 # meta-object instances for any Class::MOP::*
67 # class. All other classes will use the more
68 # normal &construct_instance.
69 sub _construct_class_instance {
71 my $options = @_ == 1 ? $_[0] : {@_};
72 my $package_name = $options->{package};
73 (defined $package_name && $package_name)
74 || confess "You must pass a package name";
76 # return the metaclass if we have it cached,
77 # and it is still defined (it has not been
78 # reaped by DESTROY yet, which can happen
79 # annoyingly enough during global destruction)
81 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
87 ? $class->_real_ref_name
90 # now create the metaclass
92 if ($class eq 'Class::MOP::Class') {
93 $meta = $class->_new($options);
97 # it is safe to use meta here because
98 # class will always be a subclass of
99 # Class::MOP::Class, which defines meta
100 $meta = $class->meta->_construct_instance($options)
103 # and check the metaclass compatibility
104 $meta->_check_metaclass_compatibility();
106 Class::MOP::store_metaclass_by_name($package_name, $meta);
109 # we need to weaken any anon classes
110 # so that they can call DESTROY properly
111 Class::MOP::weaken_metaclass($package_name) if $options->{weaken};
119 # NOTE: we need to deal with the possibility of class immutability here,
120 # and then get the name of the class appropriately
121 return $self->is_immutable
122 ? $self->_get_mutable_metaclass_name()
129 return Class::MOP::Class->initialize($class)->new_object(@_)
130 if $class ne __PACKAGE__;
132 my $options = @_ == 1 ? $_[0] : {@_};
135 # inherited from Class::MOP::Package
136 'package' => $options->{package},
139 # since the following attributes will
140 # actually be loaded from the symbol
141 # table, and actually bypass the instance
142 # entirely, we can just leave these things
143 # listed here for reference, because they
144 # should not actually have a value associated
146 'namespace' => \undef,
149 # inherited from Class::MOP::Module
151 'authority' => \undef,
153 # defined in Class::MOP::Class
154 'superclasses' => \undef,
157 'attribute_metaclass' =>
158 ( $options->{'attribute_metaclass'} || 'Class::MOP::Attribute' ),
159 'method_metaclass' =>
160 ( $options->{'method_metaclass'} || 'Class::MOP::Method' ),
161 'wrapped_method_metaclass' => (
162 $options->{'wrapped_method_metaclass'}
163 || 'Class::MOP::Method::Wrapped'
165 'instance_metaclass' =>
166 ( $options->{'instance_metaclass'} || 'Class::MOP::Instance' ),
167 'immutable_trait' => (
168 $options->{'immutable_trait'}
169 || 'Class::MOP::Class::Immutable::Trait'
171 'constructor_name' => ( $options->{constructor_name} || 'new' ),
172 'constructor_class' => (
173 $options->{constructor_class} || 'Class::MOP::Method::Constructor'
175 'destructor_class' => $options->{destructor_class},
179 ## Metaclass compatibility
181 my %base_metaclass = (
182 attribute_metaclass => 'Class::MOP::Attribute',
183 method_metaclass => 'Class::MOP::Method',
184 wrapped_method_metaclass => 'Class::MOP::Method::Wrapped',
185 instance_metaclass => 'Class::MOP::Instance',
186 constructor_class => 'Class::MOP::Method::Constructor',
187 destructor_class => 'Class::MOP::Method::Destructor',
190 sub _base_metaclasses { %base_metaclass }
193 sub _check_metaclass_compatibility {
196 my @superclasses = $self->superclasses
199 $self->_fix_metaclass_incompatibility(@superclasses);
201 my %base_metaclass = $self->_base_metaclasses;
203 # this is always okay ...
205 if ref($self) eq 'Class::MOP::Class'
207 my $meta = $self->$_;
208 !defined($meta) || $meta eq $base_metaclass{$_};
210 keys %base_metaclass;
212 for my $superclass (@superclasses) {
213 $self->_check_class_metaclass_compatibility($superclass);
216 for my $metaclass_type ( keys %base_metaclass ) {
217 next unless defined $self->$metaclass_type;
218 for my $superclass (@superclasses) {
219 $self->_check_single_metaclass_compatibility( $metaclass_type,
225 sub _check_class_metaclass_compatibility {
227 my ( $superclass_name ) = @_;
229 if (!$self->_class_metaclass_is_compatible($superclass_name)) {
230 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
232 my $super_meta_type = $super_meta->_real_ref_name;
234 confess "The metaclass of " . $self->name . " ("
235 . (ref($self)) . ")" . " is not compatible with "
236 . "the metaclass of its superclass, "
237 . $superclass_name . " (" . ($super_meta_type) . ")";
241 sub _class_metaclass_is_compatible {
243 my ( $superclass_name ) = @_;
245 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
248 my $super_meta_name = $super_meta->_real_ref_name;
250 return $self->_is_compatible_with($super_meta_name);
253 sub _check_single_metaclass_compatibility {
255 my ( $metaclass_type, $superclass_name ) = @_;
257 if (!$self->_single_metaclass_is_compatible($metaclass_type, $superclass_name)) {
258 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
259 my $metaclass_type_name = $metaclass_type;
260 $metaclass_type_name =~ s/_(?:meta)?class$//;
261 $metaclass_type_name =~ s/_/ /g;
262 confess "The $metaclass_type_name metaclass for "
263 . $self->name . " (" . ($self->$metaclass_type)
264 . ")" . " is not compatible with the "
265 . "$metaclass_type_name metaclass of its "
266 . "superclass, $superclass_name ("
267 . ($super_meta->$metaclass_type) . ")";
271 sub _single_metaclass_is_compatible {
273 my ( $metaclass_type, $superclass_name ) = @_;
275 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
278 # for instance, Moose::Meta::Class has a error_class attribute, but
279 # Class::MOP::Class doesn't - this shouldn't be an error
280 return 1 unless $super_meta->can($metaclass_type);
281 # for instance, Moose::Meta::Class has a destructor_class, but
282 # Class::MOP::Class doesn't - this shouldn't be an error
283 return 1 unless defined $super_meta->$metaclass_type;
284 # if metaclass is defined in superclass but not here, it's not compatible
285 # this is a really odd case
286 return 0 unless defined $self->$metaclass_type;
288 return $self->$metaclass_type->_is_compatible_with($super_meta->$metaclass_type);
291 sub _fix_metaclass_incompatibility {
293 my @supers = map { Class::MOP::Class->initialize($_) } @_;
296 for my $super (@supers) {
298 if $self->_can_fix_metaclass_incompatibility($super);
300 return unless $necessary;
302 for my $super (@supers) {
303 if (!$self->_class_metaclass_is_compatible($super->name)) {
304 $self->_fix_class_metaclass_incompatibility($super);
308 my %base_metaclass = $self->_base_metaclasses;
309 for my $metaclass_type (keys %base_metaclass) {
310 for my $super (@supers) {
311 if (!$self->_single_metaclass_is_compatible($metaclass_type, $super->name)) {
312 $self->_fix_single_metaclass_incompatibility(
313 $metaclass_type, $super
320 sub _can_fix_metaclass_incompatibility {
322 my ($super_meta) = @_;
324 return 1 if $self->_class_metaclass_can_be_made_compatible($super_meta);
326 my %base_metaclass = $self->_base_metaclasses;
327 for my $metaclass_type (keys %base_metaclass) {
328 return 1 if $self->_single_metaclass_can_be_made_compatible($super_meta, $metaclass_type);
334 sub _class_metaclass_can_be_made_compatible {
336 my ($super_meta) = @_;
338 return $self->_can_be_made_compatible_with($super_meta->_real_ref_name);
341 sub _single_metaclass_can_be_made_compatible {
343 my ($super_meta, $metaclass_type) = @_;
345 my $specific_meta = $self->$metaclass_type;
347 return unless $super_meta->can($metaclass_type);
348 my $super_specific_meta = $super_meta->$metaclass_type;
350 # for instance, Moose::Meta::Class has a destructor_class, but
351 # Class::MOP::Class doesn't - this shouldn't be an error
352 return unless defined $super_specific_meta;
354 # if metaclass is defined in superclass but not here, it's fixable
355 # this is a really odd case
356 return 1 unless defined $specific_meta;
358 return 1 if $specific_meta->_can_be_made_compatible_with($super_specific_meta);
361 sub _fix_class_metaclass_incompatibility {
363 my ( $super_meta ) = @_;
365 if ($self->_class_metaclass_can_be_made_compatible($super_meta)) {
367 || confess "Can't fix metaclass incompatibility for "
369 . " because it is not pristine.";
371 my $super_meta_name = $super_meta->_real_ref_name;
373 $self->_make_compatible_with($super_meta_name);
377 sub _fix_single_metaclass_incompatibility {
379 my ( $metaclass_type, $super_meta ) = @_;
381 if ($self->_single_metaclass_can_be_made_compatible($super_meta, $metaclass_type)) {
383 || confess "Can't fix metaclass incompatibility for "
385 . " because it is not pristine.";
387 my $new_metaclass = $self->$metaclass_type
388 ? $self->$metaclass_type->_get_compatible_metaclass($super_meta->$metaclass_type)
389 : $super_meta->$metaclass_type;
390 $self->{$metaclass_type} = $new_metaclass;
394 sub _restore_metaobjects_from {
398 $self->_restore_metamethods_from($old_meta);
399 $self->_restore_metaattributes_from($old_meta);
402 sub _remove_generated_metaobjects {
405 for my $attr (map { $self->get_attribute($_) } $self->get_attribute_list) {
406 $attr->remove_accessors;
410 # creating classes with MOP ...
416 unshift @args, 'package' if @args % 2 == 1;
419 (ref $options{superclasses} eq 'ARRAY')
420 || confess "You must pass an ARRAY ref of superclasses"
421 if exists $options{superclasses};
423 (ref $options{attributes} eq 'ARRAY')
424 || confess "You must pass an ARRAY ref of attributes"
425 if exists $options{attributes};
427 (ref $options{methods} eq 'HASH')
428 || confess "You must pass a HASH ref of methods"
429 if exists $options{methods};
431 my $package = delete $options{package};
432 my $superclasses = delete $options{superclasses};
433 my $attributes = delete $options{attributes};
434 my $methods = delete $options{methods};
435 my $meta_name = exists $options{meta_name}
436 ? delete $options{meta_name}
439 my $meta = $class->SUPER::create($package => %options);
441 $meta->_add_meta_method($meta_name)
442 if defined $meta_name;
444 $meta->superclasses(@{$superclasses})
445 if defined $superclasses;
447 # process attributes first, so that they can
448 # install accessors, but locally defined methods
449 # can then overwrite them. It is maybe a little odd, but
450 # I think this should be the order of things.
451 if (defined $attributes) {
452 foreach my $attr (@{$attributes}) {
453 $meta->add_attribute($attr);
456 if (defined $methods) {
457 foreach my $method_name (keys %{$methods}) {
458 $meta->add_method($method_name, $methods->{$method_name});
464 # XXX: something more intelligent here?
465 sub _anon_package_prefix { 'Class::MOP::Class::__ANON__::SERIAL::' }
467 sub create_anon_class { shift->create_anon(@_) }
468 sub is_anon_class { shift->is_anon(@_) }
470 sub _anon_cache_key {
473 # Makes something like Super::Class|Super::Class::2
475 join( '|', sort @{ $options{superclasses} || [] } ),
479 # Instance Construction & Cloning
485 # we need to protect the integrity of the
486 # Class::MOP::Class singletons here, so we
487 # delegate this to &construct_class_instance
488 # which will deal with the singletons
489 return $class->_construct_class_instance(@_)
490 if $class->name->isa('Class::MOP::Class');
491 return $class->_construct_instance(@_);
494 sub _construct_instance {
496 my $params = @_ == 1 ? $_[0] : {@_};
497 my $meta_instance = $class->get_meta_instance();
499 # the code below is almost certainly incorrect
500 # but this is foreign inheritance, so we might
501 # have to kludge it in the end.
503 if (my $instance_class = blessed($params->{__INSTANCE__})) {
504 ($instance_class eq $class->name)
505 || confess "Objects passed as the __INSTANCE__ parameter must "
506 . "already be blessed into the correct class, but "
507 . "$params->{__INSTANCE__} is not a " . $class->name;
508 $instance = $params->{__INSTANCE__};
510 elsif (exists $params->{__INSTANCE__}) {
511 confess "The __INSTANCE__ parameter must be a blessed reference, not "
512 . $params->{__INSTANCE__};
515 $instance = $meta_instance->create_instance();
517 foreach my $attr ($class->get_all_attributes()) {
518 $attr->initialize_instance_slot($meta_instance, $instance, $params);
520 if (Class::MOP::metaclass_is_weak($class->name)) {
521 $meta_instance->_set_mop_slot($instance, $class);
526 sub _inline_new_object {
530 'my $class = shift;',
531 '$class = Scalar::Util::blessed($class) || $class;',
532 $self->_inline_fallback_constructor('$class'),
533 $self->_inline_params('$params', '$class'),
534 $self->_inline_generate_instance('$instance', '$class'),
535 $self->_inline_slot_initializers,
536 $self->_inline_preserve_weak_metaclasses,
537 $self->_inline_extra_init,
542 sub _inline_fallback_constructor {
546 'return ' . $self->_generate_fallback_constructor($class),
547 'if ' . $class . ' ne \'' . $self->name . '\';',
551 sub _generate_fallback_constructor {
554 return 'Class::MOP::Class->initialize(' . $class . ')->new_object(@_)',
559 my ($params, $class) = @_;
561 'my ' . $params . ' = @_ == 1 ? $_[0] : {@_};',
565 sub _inline_generate_instance {
567 my ($inst, $class) = @_;
569 'my ' . $inst . ' = ' . $self->_inline_create_instance($class) . ';',
573 sub _inline_create_instance {
576 return $self->get_meta_instance->inline_create_instance(@_);
579 sub _inline_slot_initializers {
584 return map { $self->_inline_slot_initializer($_, $idx++) }
585 sort { $a->name cmp $b->name } $self->get_all_attributes;
588 sub _inline_slot_initializer {
590 my ($attr, $idx) = @_;
592 if (defined(my $init_arg = $attr->init_arg)) {
594 'if (exists $params->{\'' . $init_arg . '\'}) {',
595 $self->_inline_init_attr_from_constructor($attr, $idx),
598 if (my @default = $self->_inline_init_attr_from_default($attr, $idx)) {
607 elsif (my @default = $self->_inline_init_attr_from_default($attr, $idx)) {
619 sub _inline_init_attr_from_constructor {
621 my ($attr, $idx) = @_;
623 my @initial_value = $attr->_inline_set_value(
624 '$instance', '$params->{\'' . $attr->init_arg . '\'}',
627 push @initial_value, (
628 '$attrs->[' . $idx . ']->set_initial_value(',
630 $attr->_inline_instance_get('$instance'),
632 ) if $attr->has_initializer;
634 return @initial_value;
637 sub _inline_init_attr_from_default {
639 my ($attr, $idx) = @_;
641 my $default = $self->_inline_default_value($attr, $idx);
642 return unless $default;
644 my @initial_value = $attr->_inline_set_value('$instance', $default);
646 push @initial_value, (
647 '$attrs->[' . $idx . ']->set_initial_value(',
649 $attr->_inline_instance_get('$instance'),
651 ) if $attr->has_initializer;
653 return @initial_value;
656 sub _inline_default_value {
658 my ($attr, $index) = @_;
660 if ($attr->has_default) {
662 # default values can either be CODE refs
663 # in which case we need to call them. Or
664 # they can be scalars (strings/numbers)
665 # in which case we can just deal with them
666 # in the code we eval.
667 if ($attr->is_default_a_coderef) {
668 return '$defaults->[' . $index . ']->($instance)';
671 return '$defaults->[' . $index . ']';
674 elsif ($attr->has_builder) {
675 return '$instance->' . $attr->builder;
682 sub _inline_preserve_weak_metaclasses {
684 if (Class::MOP::metaclass_is_weak($self->name)) {
686 $self->_inline_set_mop_slot(
687 '$instance', 'Class::MOP::class_of($class)'
696 sub _inline_extra_init { }
698 sub _eval_environment {
701 my @attrs = sort { $a->name cmp $b->name } $self->get_all_attributes;
703 my $defaults = [map { $_->default } @attrs];
706 '$defaults' => \$defaults,
711 sub get_meta_instance {
713 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
716 sub _create_meta_instance {
719 my $instance = $self->instance_metaclass->new(
720 associated_metaclass => $self,
721 attributes => [ $self->get_all_attributes() ],
724 $self->add_meta_instance_dependencies()
725 if $instance->is_dependent_on_superclasses();
730 # TODO: this is actually not being used!
731 sub _inline_rebless_instance {
734 return $self->get_meta_instance->inline_rebless_instance_structure(@_);
737 sub _inline_get_mop_slot {
740 return $self->get_meta_instance->_inline_get_mop_slot(@_);
743 sub _inline_set_mop_slot {
746 return $self->get_meta_instance->_inline_set_mop_slot(@_);
749 sub _inline_clear_mop_slot {
752 return $self->get_meta_instance->_inline_clear_mop_slot(@_);
757 my $instance = shift;
758 (blessed($instance) && $instance->isa($class->name))
759 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
762 # we need to protect the integrity of the
763 # Class::MOP::Class singletons here, they
764 # should not be cloned.
765 return $instance if $instance->isa('Class::MOP::Class');
766 $class->_clone_instance($instance, @_);
769 sub _clone_instance {
770 my ($class, $instance, %params) = @_;
772 || confess "You can only clone instances, ($instance) is not a blessed instance";
773 my $meta_instance = $class->get_meta_instance();
774 my $clone = $meta_instance->clone_instance($instance);
775 foreach my $attr ($class->get_all_attributes()) {
776 if ( defined( my $init_arg = $attr->init_arg ) ) {
777 if (exists $params{$init_arg}) {
778 $attr->set_value($clone, $params{$init_arg});
785 sub _force_rebless_instance {
786 my ($self, $instance, %params) = @_;
787 my $old_metaclass = Class::MOP::class_of($instance);
789 $old_metaclass->rebless_instance_away($instance, $self, %params)
792 my $meta_instance = $self->get_meta_instance;
794 if (Class::MOP::metaclass_is_weak($old_metaclass->name)) {
795 $meta_instance->_clear_mop_slot($instance);
799 # we use $_[1] here because of t/cmop/rebless_overload.t regressions
801 $meta_instance->rebless_instance_structure($_[1], $self);
803 $self->_fixup_attributes_after_rebless($instance, $old_metaclass, %params);
805 if (Class::MOP::metaclass_is_weak($self->name)) {
806 $meta_instance->_set_mop_slot($instance, $self);
810 sub rebless_instance {
811 my ($self, $instance, %params) = @_;
812 my $old_metaclass = Class::MOP::class_of($instance);
814 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
815 $self->name->isa($old_class)
816 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
818 $self->_force_rebless_instance($_[1], %params);
823 sub rebless_instance_back {
824 my ( $self, $instance ) = @_;
825 my $old_metaclass = Class::MOP::class_of($instance);
828 = $old_metaclass ? $old_metaclass->name : blessed($instance);
829 $old_class->isa( $self->name )
831 "You may rebless only into a superclass of ($old_class), of which ("
835 $self->_force_rebless_instance($_[1]);
840 sub rebless_instance_away {
841 # this intentionally does nothing, it is just a hook
844 sub _fixup_attributes_after_rebless {
846 my ($instance, $rebless_from, %params) = @_;
847 my $meta_instance = $self->get_meta_instance;
849 for my $attr ( $rebless_from->get_all_attributes ) {
850 next if $self->find_attribute_by_name( $attr->name );
851 $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
854 foreach my $attr ( $self->get_all_attributes ) {
855 if ( $attr->has_value($instance) ) {
856 if ( defined( my $init_arg = $attr->init_arg ) ) {
857 $params{$init_arg} = $attr->get_value($instance)
858 unless exists $params{$init_arg};
861 $attr->set_value($instance, $attr->get_value($instance));
866 foreach my $attr ($self->get_all_attributes) {
867 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
871 sub _attach_attribute {
872 my ($self, $attribute) = @_;
873 $attribute->attach_to_class($self);
876 sub _post_add_attribute {
877 my ( $self, $attribute ) = @_;
879 $self->invalidate_meta_instances;
881 # invalidate package flag here
884 $attribute->install_accessors;
887 $self->remove_attribute( $attribute->name );
892 sub remove_attribute {
895 my $removed_attribute = $self->SUPER::remove_attribute(@_)
898 $self->invalidate_meta_instances;
900 $removed_attribute->remove_accessors;
901 $removed_attribute->detach_from_class;
903 return$removed_attribute;
906 sub find_attribute_by_name {
907 my ( $self, $attr_name ) = @_;
909 foreach my $class ( $self->linearized_isa ) {
910 # fetch the meta-class ...
911 my $meta = Class::MOP::Class->initialize($class);
912 return $meta->get_attribute($attr_name)
913 if $meta->has_attribute($attr_name);
919 sub get_all_attributes {
921 my %attrs = map { %{ Class::MOP::Class->initialize($_)->_attribute_map } }
922 reverse $self->linearized_isa;
923 return values %attrs;
931 my $isa = $self->get_or_add_package_symbol('@ISA');
938 # on 5.8 and below, we need to call
939 # a method to get Perl to detect
940 # a cycle in the class hierarchy
941 my $class = $self->name;
945 # we need to check the metaclass
946 # compatibility here so that we can
947 # be sure that the superclass is
948 # not potentially creating an issues
949 # we don't know about
951 $self->_check_metaclass_compatibility();
952 $self->_superclasses_updated();
958 sub _superclasses_updated {
960 $self->update_meta_instance_dependencies();
961 # keep strong references to all our parents, so they don't disappear if
962 # they are anon classes and don't have any direct instances
963 $self->_superclass_metas(
964 map { Class::MOP::class_of($_) } $self->superclasses
968 sub _superclass_metas {
970 $self->{_superclass_metas} = [@_];
975 my $super_class = $self->name;
977 return @{ $super_class->mro::get_isarev() };
980 sub direct_subclasses {
982 my $super_class = $self->name;
987 } Class::MOP::Class->initialize($_)->superclasses
992 return @{ mro::get_linear_isa( (shift)->name ) };
995 sub class_precedence_list {
997 my $name = $self->name;
999 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
1001 # We need to check for circular inheritance here
1002 # if we are are not on 5.10, cause 5.8 detects it
1003 # late. This will do nothing if all is well, and
1004 # blow up otherwise. Yes, it's an ugly hack, better
1005 # suggestions are welcome.
1007 ($name || return)->isa('This is a test for circular inheritance')
1010 # if our mro is c3, we can
1011 # just grab the linear_isa
1012 if (mro::get_mro($name) eq 'c3') {
1013 return @{ mro::get_linear_isa($name) }
1017 # we can't grab the linear_isa for dfs
1018 # since it has all the duplicates
1023 Class::MOP::Class->initialize($_)->class_precedence_list()
1024 } $self->superclasses()
1032 my $fetch_and_prepare_method = sub {
1033 my ($self, $method_name) = @_;
1034 my $wrapped_metaclass = $self->wrapped_method_metaclass;
1036 my $method = $self->get_method($method_name);
1037 # if we dont have local ...
1039 # try to find the next method
1040 $method = $self->find_next_method_by_name($method_name);
1041 # die if it does not exist
1043 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
1044 # and now make sure to wrap it
1045 # even if it is already wrapped
1046 # because we need a new sub ref
1047 $method = $wrapped_metaclass->wrap($method,
1048 package_name => $self->name,
1049 name => $method_name,
1053 # now make sure we wrap it properly
1054 $method = $wrapped_metaclass->wrap($method,
1055 package_name => $self->name,
1056 name => $method_name,
1057 ) unless $method->isa($wrapped_metaclass);
1059 $self->add_method($method_name => $method);
1063 sub add_before_method_modifier {
1064 my ($self, $method_name, $method_modifier) = @_;
1065 (defined $method_name && length $method_name)
1066 || confess "You must pass in a method name";
1067 my $method = $fetch_and_prepare_method->($self, $method_name);
1068 $method->add_before_modifier(
1069 subname(':before' => $method_modifier)
1073 sub add_after_method_modifier {
1074 my ($self, $method_name, $method_modifier) = @_;
1075 (defined $method_name && length $method_name)
1076 || confess "You must pass in a method name";
1077 my $method = $fetch_and_prepare_method->($self, $method_name);
1078 $method->add_after_modifier(
1079 subname(':after' => $method_modifier)
1083 sub add_around_method_modifier {
1084 my ($self, $method_name, $method_modifier) = @_;
1085 (defined $method_name && length $method_name)
1086 || confess "You must pass in a method name";
1087 my $method = $fetch_and_prepare_method->($self, $method_name);
1088 $method->add_around_modifier(
1089 subname(':around' => $method_modifier)
1094 # the methods above used to be named like this:
1095 # ${pkg}::${method}:(before|after|around)
1096 # but this proved problematic when using one modifier
1097 # to wrap multiple methods (something which is likely
1098 # to happen pretty regularly IMO). So instead of naming
1099 # it like this, I have chosen to just name them purely
1100 # with their modifier names, like so:
1101 # :(before|after|around)
1102 # The fact is that in a stack trace, it will be fairly
1103 # evident from the context what method they are attached
1104 # to, and so don't need the fully qualified name.
1107 sub find_method_by_name {
1108 my ($self, $method_name) = @_;
1109 (defined $method_name && length $method_name)
1110 || confess "You must define a method name to find";
1111 foreach my $class ($self->linearized_isa) {
1112 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1113 return $method if defined $method;
1118 sub get_all_methods {
1122 for my $class ( reverse $self->linearized_isa ) {
1123 my $meta = Class::MOP::Class->initialize($class);
1125 $methods{ $_->name } = $_ for $meta->_get_local_methods;
1128 return values %methods;
1131 sub get_all_method_names {
1134 return grep { !$uniq{$_}++ } map { Class::MOP::Class->initialize($_)->get_method_list } $self->linearized_isa;
1137 sub find_all_methods_by_name {
1138 my ($self, $method_name) = @_;
1139 (defined $method_name && length $method_name)
1140 || confess "You must define a method name to find";
1142 foreach my $class ($self->linearized_isa) {
1143 # fetch the meta-class ...
1144 my $meta = Class::MOP::Class->initialize($class);
1146 name => $method_name,
1148 code => $meta->get_method($method_name)
1149 } if $meta->has_method($method_name);
1154 sub find_next_method_by_name {
1155 my ($self, $method_name) = @_;
1156 (defined $method_name && length $method_name)
1157 || confess "You must define a method name to find";
1158 my @cpl = $self->linearized_isa;
1159 shift @cpl; # discard ourselves
1160 foreach my $class (@cpl) {
1161 my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1162 return $method if defined $method;
1167 sub update_meta_instance_dependencies {
1170 if ( $self->{meta_instance_dependencies} ) {
1171 return $self->add_meta_instance_dependencies;
1175 sub add_meta_instance_dependencies {
1178 $self->remove_meta_instance_dependencies;
1180 my @attrs = $self->get_all_attributes();
1183 my @classes = grep { not $seen{ $_->name }++ }
1184 map { $_->associated_class } @attrs;
1186 foreach my $class (@classes) {
1187 $class->add_dependent_meta_instance($self);
1190 $self->{meta_instance_dependencies} = \@classes;
1193 sub remove_meta_instance_dependencies {
1196 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
1197 foreach my $class (@$classes) {
1198 $class->remove_dependent_meta_instance($self);
1208 sub add_dependent_meta_instance {
1209 my ( $self, $metaclass ) = @_;
1210 push @{ $self->{dependent_meta_instances} }, $metaclass;
1213 sub remove_dependent_meta_instance {
1214 my ( $self, $metaclass ) = @_;
1215 my $name = $metaclass->name;
1216 @$_ = grep { $_->name ne $name } @$_
1217 for $self->{dependent_meta_instances};
1220 sub invalidate_meta_instances {
1222 $_->invalidate_meta_instance()
1223 for $self, @{ $self->{dependent_meta_instances} };
1226 sub invalidate_meta_instance {
1228 undef $self->{_meta_instance};
1231 # check if we can reinitialize
1235 # if any local attr is defined
1236 return if $self->get_attribute_list;
1238 # or any non-declared methods
1239 for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1240 return if $method->isa("Class::MOP::Method::Generated");
1241 # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1249 sub is_mutable { 1 }
1250 sub is_immutable { 0 }
1252 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1254 sub _immutable_options {
1255 my ( $self, @args ) = @_;
1258 inline_accessors => 1,
1259 inline_constructor => 1,
1260 inline_destructor => 0,
1262 immutable_trait => $self->immutable_trait,
1263 constructor_name => $self->constructor_name,
1264 constructor_class => $self->constructor_class,
1265 destructor_class => $self->destructor_class,
1270 sub make_immutable {
1271 my ( $self, @args ) = @_;
1273 return if not $self->is_mutable;
1275 my ($file, $line) = (caller)[1..2];
1277 $self->_initialize_immutable(
1280 $self->_immutable_options(@args),
1282 $self->_rebless_as_immutable(@args);
1289 if ( $self->is_immutable ) {
1290 my @args = $self->immutable_options;
1291 $self->_rebless_as_mutable();
1292 $self->_remove_inlined_code(@args);
1293 delete $self->{__immutable};
1301 sub _rebless_as_immutable {
1302 my ( $self, @args ) = @_;
1304 $self->{__immutable}{original_class} = ref $self;
1306 bless $self => $self->_immutable_metaclass(@args);
1309 sub _immutable_metaclass {
1310 my ( $self, %args ) = @_;
1312 if ( my $class = $args{immutable_metaclass} ) {
1316 my $trait = $args{immutable_trait} = $self->immutable_trait
1317 || confess "no immutable trait specified for $self";
1319 my $meta = $self->meta;
1320 my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1324 if ( $meta_attr and $trait eq $meta_attr->default ) {
1325 # if the trait is the same as the default we try and pick a
1326 # predictable name for the immutable metaclass
1327 $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1330 $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1331 $trait, 'ForMetaClass', ref($self);
1335 if Class::MOP::is_class_loaded($class_name);
1337 # If the metaclass is a subclass of CMOP::Class which has had
1338 # metaclass roles applied (via Moose), then we want to make sure
1339 # that we preserve that anonymous class (see Fey::ORM for an
1340 # example of where this matters).
1341 my $meta_name = $meta->_real_ref_name;
1343 my $immutable_meta = $meta_name->create(
1345 superclasses => [ ref $self ],
1348 Class::MOP::MiniTrait::apply( $immutable_meta, $trait );
1350 $immutable_meta->make_immutable(
1351 inline_constructor => 0,
1352 inline_accessors => 0,
1358 sub _remove_inlined_code {
1361 $self->remove_method( $_->name ) for $self->_inlined_methods;
1363 delete $self->{__immutable}{inlined_methods};
1366 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1368 sub _add_inlined_method {
1369 my ( $self, $method ) = @_;
1371 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1374 sub _initialize_immutable {
1375 my ( $self, %args ) = @_;
1377 $self->{__immutable}{options} = \%args;
1378 $self->_install_inlined_code(%args);
1381 sub _install_inlined_code {
1382 my ( $self, %args ) = @_;
1385 $self->_inline_accessors(%args) if $args{inline_accessors};
1386 $self->_inline_constructor(%args) if $args{inline_constructor};
1387 $self->_inline_destructor(%args) if $args{inline_destructor};
1390 sub _rebless_as_mutable {
1393 bless $self, $self->_get_mutable_metaclass_name;
1398 sub _inline_accessors {
1401 foreach my $attr_name ( $self->get_attribute_list ) {
1402 $self->get_attribute($attr_name)->install_accessors(1);
1406 sub _inline_constructor {
1407 my ( $self, %args ) = @_;
1409 my $name = $args{constructor_name};
1410 # A class may not even have a constructor, and that's okay.
1411 return unless defined $name;
1413 if ( $self->has_method($name) && !$args{replace_constructor} ) {
1414 my $class = $self->name;
1415 warn "Not inlining a constructor for $class since it defines"
1416 . " its own constructor.\n"
1417 . "If you are certain you don't need to inline your"
1418 . " constructor, specify inline_constructor => 0 in your"
1419 . " call to $class->meta->make_immutable\n";
1423 my $constructor_class = $args{constructor_class};
1425 Class::MOP::load_class($constructor_class);
1427 my $constructor = $constructor_class->new(
1431 package_name => $self->name,
1433 definition_context => {
1434 description => "constructor " . $self->name . "::" . $name,
1435 file => $args{file},
1436 line => $args{line},
1440 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1441 $self->add_method( $name => $constructor );
1442 $self->_add_inlined_method($constructor);
1446 sub _inline_destructor {
1447 my ( $self, %args ) = @_;
1449 ( exists $args{destructor_class} && defined $args{destructor_class} )
1450 || confess "The 'inline_destructor' option is present, but "
1451 . "no destructor class was specified";
1453 if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1454 my $class = $self->name;
1455 warn "Not inlining a destructor for $class since it defines"
1456 . " its own destructor.\n";
1460 my $destructor_class = $args{destructor_class};
1462 Class::MOP::load_class($destructor_class);
1464 return unless $destructor_class->is_needed($self);
1466 my $destructor = $destructor_class->new(
1469 package_name => $self->name,
1471 definition_context => {
1472 description => "destructor " . $self->name . "::DESTROY",
1473 file => $args{file},
1474 line => $args{line},
1478 if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1479 $self->add_method( 'DESTROY' => $destructor );
1480 $self->_add_inlined_method($destructor);
1486 # ABSTRACT: Class Meta Object
1494 # assuming that class Foo
1495 # has been defined, you can
1497 # use this for introspection ...
1499 # add a method to Foo ...
1500 Foo->meta->add_method( 'bar' => sub {...} )
1502 # get a list of all the classes searched
1503 # the method dispatcher in the correct order
1504 Foo->meta->class_precedence_list()
1506 # remove a method from Foo
1507 Foo->meta->remove_method('bar');
1509 # or use this to actually create classes ...
1511 Class::MOP::Class->create(
1514 superclasses => ['Foo'],
1516 Class::MOP::Attribute->new('$bar'),
1517 Class::MOP::Attribute->new('$baz'),
1520 calculate_bar => sub {...},
1521 construct_baz => sub {...}
1528 The Class Protocol is the largest and most complex part of the
1529 Class::MOP meta-object protocol. It controls the introspection and
1530 manipulation of Perl 5 classes, and it can create them as well. The
1531 best way to understand what this module can do is to read the
1532 documentation for each of its methods.
1536 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1540 =head2 Class construction
1542 These methods all create new C<Class::MOP::Class> objects. These
1543 objects can represent existing classes or they can be used to create
1544 new classes from scratch.
1546 The metaclass object for a given class is a singleton. If you attempt
1547 to create a metaclass for the same class twice, you will just get the
1552 =item B<< Class::MOP::Class->create($package_name, %options) >>
1554 This method creates a new C<Class::MOP::Class> object with the given
1555 package name. It accepts a number of options:
1561 An optional version number for the newly created package.
1565 An optional authority for the newly created package.
1567 =item * superclasses
1569 An optional array reference of superclass names.
1573 An optional hash reference of methods for the class. The keys of the
1574 hash reference are method names and values are subroutine references.
1578 An optional array reference of L<Class::MOP::Attribute> objects.
1582 Specifies the name to install the C<meta> method for this class under.
1583 If it is not passed, C<meta> is assumed, and if C<undef> is explicitly
1584 given, no meta method will be installed.
1588 If true, the metaclass that is stored in the global cache will be a
1591 Classes created in this way are destroyed once the metaclass they are
1592 attached to goes out of scope, and will be removed from Perl's internal
1595 All instances of a class with a weakened metaclass keep a special
1596 reference to the metaclass object, which prevents the metaclass from
1597 going out of scope while any instances exist.
1599 This only works if the instance is based on a hash reference, however.
1603 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1605 This method works just like C<< Class::MOP::Class->create >> but it
1606 creates an "anonymous" class. In fact, the class does have a name, but
1607 that name is a unique name generated internally by this module.
1609 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1610 parameters that C<create> accepts.
1612 Anonymous classes default to C<< weaken => 1 >>, although this can be
1615 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1617 This method will initialize a C<Class::MOP::Class> object for the
1618 named package. Unlike C<create>, this method I<will not> create a new
1621 The purpose of this method is to retrieve a C<Class::MOP::Class>
1622 object for introspecting an existing class.
1624 If an existing C<Class::MOP::Class> object exists for the named
1625 package, it will be returned, and any options provided will be
1628 If the object does not yet exist, it will be created.
1630 The valid options that can be passed to this method are
1631 C<attribute_metaclass>, C<method_metaclass>,
1632 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1633 optional, and default to the appropriate class in the C<Class::MOP>
1638 =head2 Object instance construction and cloning
1640 These methods are all related to creating and/or cloning object
1645 =item B<< $metaclass->clone_object($instance, %params) >>
1647 This method clones an existing object instance. Any parameters you
1648 provide are will override existing attribute values in the object.
1650 This is a convenience method for cloning an object instance, then
1651 blessing it into the appropriate package.
1653 You could implement a clone method in your class, using this method:
1656 my ($self, %params) = @_;
1657 $self->meta->clone_object($self, %params);
1660 =item B<< $metaclass->rebless_instance($instance, %params) >>
1662 This method changes the class of C<$instance> to the metaclass's class.
1664 You can only rebless an instance into a subclass of its current
1665 class. If you pass any additional parameters, these will be treated
1666 like constructor parameters and used to initialize the object's
1667 attributes. Any existing attributes that are already set will be
1670 Before reblessing the instance, this method will call
1671 C<rebless_instance_away> on the instance's current metaclass. This method
1672 will be passed the instance, the new metaclass, and any parameters
1673 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1674 does nothing; it is merely a hook.
1676 =item B<< $metaclass->rebless_instance_back($instance) >>
1678 Does the same thing as C<rebless_instance>, except that you can only
1679 rebless an instance into one of its superclasses. Any attributes that
1680 do not exist in the superclass will be deinitialized.
1682 This is a much more dangerous operation than C<rebless_instance>,
1683 especially when multiple inheritance is involved, so use this carefully!
1685 =item B<< $metaclass->new_object(%params) >>
1687 This method is used to create a new object of the metaclass's
1688 class. Any parameters you provide are used to initialize the
1689 instance's attributes. A special C<__INSTANCE__> key can be passed to
1690 provide an already generated instance, rather than having Class::MOP
1691 generate it for you. This is mostly useful for using Class::MOP with
1692 foreign classes which generate instances using their own constructors.
1694 =item B<< $metaclass->instance_metaclass >>
1696 Returns the class name of the instance metaclass. See
1697 L<Class::MOP::Instance> for more information on the instance
1700 =item B<< $metaclass->get_meta_instance >>
1702 Returns an instance of the C<instance_metaclass> to be used in the
1703 construction of a new instance of the class.
1707 =head2 Informational predicates
1709 These are a few predicate methods for asking information about the
1714 =item B<< $metaclass->is_anon_class >>
1716 This returns true if the class was created by calling C<<
1717 Class::MOP::Class->create_anon_class >>.
1719 =item B<< $metaclass->is_mutable >>
1721 This returns true if the class is still mutable.
1723 =item B<< $metaclass->is_immutable >>
1725 This returns true if the class has been made immutable.
1727 =item B<< $metaclass->is_pristine >>
1729 A class is I<not> pristine if it has non-inherited attributes or if it
1730 has any generated methods.
1734 =head2 Inheritance Relationships
1738 =item B<< $metaclass->superclasses(@superclasses) >>
1740 This is a read-write accessor which represents the superclass
1741 relationships of the metaclass's class.
1743 This is basically sugar around getting and setting C<@ISA>.
1745 =item B<< $metaclass->class_precedence_list >>
1747 This returns a list of all of the class's ancestor classes. The
1748 classes are returned in method dispatch order.
1750 =item B<< $metaclass->linearized_isa >>
1752 This returns a list based on C<class_precedence_list> but with all
1755 =item B<< $metaclass->subclasses >>
1757 This returns a list of all subclasses for this class, even indirect
1760 =item B<< $metaclass->direct_subclasses >>
1762 This returns a list of immediate subclasses for this class, which does not
1763 include indirect subclasses.
1767 =head2 Method introspection and creation
1769 These methods allow you to introspect a class's methods, as well as
1770 add, remove, or change methods.
1772 Determining what is truly a method in a Perl 5 class requires some
1773 heuristics (aka guessing).
1775 Methods defined outside the package with a fully qualified name (C<sub
1776 Package::name { ... }>) will be included. Similarly, methods named
1777 with a fully qualified name using L<Sub::Name> are also included.
1779 However, we attempt to ignore imported functions.
1781 Ultimately, we are using heuristics to determine what truly is a
1782 method in a class, and these heuristics may get the wrong answer in
1783 some edge cases. However, for most "normal" cases the heuristics work
1788 =item B<< $metaclass->get_method($method_name) >>
1790 This will return a L<Class::MOP::Method> for the specified
1791 C<$method_name>. If the class does not have the specified method, it
1794 =item B<< $metaclass->has_method($method_name) >>
1796 Returns a boolean indicating whether or not the class defines the
1797 named method. It does not include methods inherited from parent
1800 =item B<< $metaclass->get_method_list >>
1802 This will return a list of method I<names> for all methods defined in
1805 =item B<< $metaclass->add_method($method_name, $method) >>
1807 This method takes a method name and a subroutine reference, and adds
1808 the method to the class.
1810 The subroutine reference can be a L<Class::MOP::Method>, and you are
1811 strongly encouraged to pass a meta method object instead of a code
1812 reference. If you do so, that object gets stored as part of the
1813 class's method map directly. If not, the meta information will have to
1814 be recreated later, and may be incorrect.
1816 If you provide a method object, this method will clone that object if
1817 the object's package name does not match the class name. This lets us
1818 track the original source of any methods added from other classes
1819 (notably Moose roles).
1821 =item B<< $metaclass->remove_method($method_name) >>
1823 Remove the named method from the class. This method returns the
1824 L<Class::MOP::Method> object for the method.
1826 =item B<< $metaclass->method_metaclass >>
1828 Returns the class name of the method metaclass, see
1829 L<Class::MOP::Method> for more information on the method metaclass.
1831 =item B<< $metaclass->wrapped_method_metaclass >>
1833 Returns the class name of the wrapped method metaclass, see
1834 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1837 =item B<< $metaclass->get_all_methods >>
1839 This will traverse the inheritance hierarchy and return a list of all
1840 the L<Class::MOP::Method> objects for this class and its parents.
1842 =item B<< $metaclass->find_method_by_name($method_name) >>
1844 This will return a L<Class::MOP::Method> for the specified
1845 C<$method_name>. If the class does not have the specified method, it
1848 Unlike C<get_method>, this method I<will> look for the named method in
1851 =item B<< $metaclass->get_all_method_names >>
1853 This will return a list of method I<names> for all of this class's
1854 methods, including inherited methods.
1856 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1858 This method looks for the named method in the class and all of its
1859 parents. It returns every matching method it finds in the inheritance
1860 tree, so it returns a list of methods.
1862 Each method is returned as a hash reference with three keys. The keys
1863 are C<name>, C<class>, and C<code>. The C<code> key has a
1864 L<Class::MOP::Method> object as its value.
1866 The list of methods is distinct.
1868 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1870 This method returns the first method in any superclass matching the
1871 given name. It is effectively the method that C<SUPER::$method_name>
1876 =head2 Attribute introspection and creation
1878 Because Perl 5 does not have a core concept of attributes in classes,
1879 we can only return information about attributes which have been added
1880 via this class's methods. We cannot discover information about
1881 attributes which are defined in terms of "regular" Perl 5 methods.
1885 =item B<< $metaclass->get_attribute($attribute_name) >>
1887 This will return a L<Class::MOP::Attribute> for the specified
1888 C<$attribute_name>. If the class does not have the specified
1889 attribute, it returns C<undef>.
1891 NOTE that get_attribute does not search superclasses, for that you
1892 need to use C<find_attribute_by_name>.
1894 =item B<< $metaclass->has_attribute($attribute_name) >>
1896 Returns a boolean indicating whether or not the class defines the
1897 named attribute. It does not include attributes inherited from parent
1900 =item B<< $metaclass->get_attribute_list >>
1902 This will return a list of attributes I<names> for all attributes
1903 defined in this class. Note that this operates on the current class
1904 only, it does not traverse the inheritance hierarchy.
1906 =item B<< $metaclass->get_all_attributes >>
1908 This will traverse the inheritance hierarchy and return a list of all
1909 the L<Class::MOP::Attribute> objects for this class and its parents.
1911 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1913 This will return a L<Class::MOP::Attribute> for the specified
1914 C<$attribute_name>. If the class does not have the specified
1915 attribute, it returns C<undef>.
1917 Unlike C<get_attribute>, this attribute I<will> look for the named
1918 attribute in superclasses.
1920 =item B<< $metaclass->add_attribute(...) >>
1922 This method accepts either an existing L<Class::MOP::Attribute>
1923 object or parameters suitable for passing to that class's C<new>
1926 The attribute provided will be added to the class.
1928 Any accessor methods defined by the attribute will be added to the
1929 class when the attribute is added.
1931 If an attribute of the same name already exists, the old attribute
1932 will be removed first.
1934 =item B<< $metaclass->remove_attribute($attribute_name) >>
1936 This will remove the named attribute from the class, and
1937 L<Class::MOP::Attribute> object.
1939 Removing an attribute also removes any accessor methods defined by the
1942 However, note that removing an attribute will only affect I<future>
1943 object instances created for this class, not existing instances.
1945 =item B<< $metaclass->attribute_metaclass >>
1947 Returns the class name of the attribute metaclass for this class. By
1948 default, this is L<Class::MOP::Attribute>.
1952 =head2 Class Immutability
1954 Making a class immutable "freezes" the class definition. You can no
1955 longer call methods which alter the class, such as adding or removing
1956 methods or attributes.
1958 Making a class immutable lets us optimize the class by inlining some
1959 methods, and also allows us to optimize some methods on the metaclass
1962 After immutabilization, the metaclass object will cache most informational
1963 methods that returns information about methods or attributes. Methods which
1964 would alter the class, such as C<add_attribute> and C<add_method>, will
1965 throw an error on an immutable metaclass object.
1967 The immutabilization system in L<Moose> takes much greater advantage
1968 of the inlining features than Class::MOP itself does.
1972 =item B<< $metaclass->make_immutable(%options) >>
1974 This method will create an immutable transformer and use it to make
1975 the class and its metaclass object immutable.
1977 This method accepts the following options:
1981 =item * inline_accessors
1983 =item * inline_constructor
1985 =item * inline_destructor
1987 These are all booleans indicating whether the specified method(s)
1990 By default, accessors and the constructor are inlined, but not the
1993 =item * immutable_trait
1995 The name of a class which will be used as a parent class for the
1996 metaclass object being made immutable. This "trait" implements the
1997 post-immutability functionality of the metaclass (but not the
1998 transformation itself).
2000 This defaults to L<Class::MOP::Class::Immutable::Trait>.
2002 =item * constructor_name
2004 This is the constructor method name. This defaults to "new".
2006 =item * constructor_class
2008 The name of the method metaclass for constructors. It will be used to
2009 generate the inlined constructor. This defaults to
2010 "Class::MOP::Method::Constructor".
2012 =item * replace_constructor
2014 This is a boolean indicating whether an existing constructor should be
2015 replaced when inlining a constructor. This defaults to false.
2017 =item * destructor_class
2019 The name of the method metaclass for destructors. It will be used to
2020 generate the inlined destructor. This defaults to
2021 "Class::MOP::Method::Denstructor".
2023 =item * replace_destructor
2025 This is a boolean indicating whether an existing destructor should be
2026 replaced when inlining a destructor. This defaults to false.
2030 =item B<< $metaclass->immutable_options >>
2032 Returns a hash of the options used when making the class immutable, including
2033 both defaults and anything supplied by the user in the call to C<<
2034 $metaclass->make_immutable >>. This is useful if you need to temporarily make
2035 a class mutable and then restore immutability as it was before.
2037 =item B<< $metaclass->make_mutable >>
2039 Calling this method reverse the immutabilization transformation.
2043 =head2 Method Modifiers
2045 Method modifiers are hooks which allow a method to be wrapped with
2046 I<before>, I<after> and I<around> method modifiers. Every time a
2047 method is called, its modifiers are also called.
2049 A class can modify its own methods, as well as methods defined in
2052 =head3 How method modifiers work?
2054 Method modifiers work by wrapping the original method and then
2055 replacing it in the class's symbol table. The wrappers will handle
2056 calling all the modifiers in the appropriate order and preserving the
2057 calling context for the original method.
2059 The return values of C<before> and C<after> modifiers are
2060 ignored. This is because their purpose is B<not> to filter the input
2061 and output of the primary method (this is done with an I<around>
2064 This may seem like an odd restriction to some, but doing this allows
2065 for simple code to be added at the beginning or end of a method call
2066 without altering the function of the wrapped method or placing any
2067 extra responsibility on the code of the modifier.
2069 Of course if you have more complex needs, you can use the C<around>
2070 modifier which allows you to change both the parameters passed to the
2071 wrapped method, as well as its return value.
2073 Before and around modifiers are called in last-defined-first-called
2074 order, while after modifiers are called in first-defined-first-called
2075 order. So the call tree might looks something like this:
2087 =head3 What is the performance impact?
2089 Of course there is a performance cost associated with method
2090 modifiers, but we have made every effort to make that cost directly
2091 proportional to the number of modifier features you use.
2093 The wrapping method does its best to B<only> do as much work as it
2094 absolutely needs to. In order to do this we have moved some of the
2095 performance costs to set-up time, where they are easier to amortize.
2097 All this said, our benchmarks have indicated the following:
2099 simple wrapper with no modifiers 100% slower
2100 simple wrapper with simple before modifier 400% slower
2101 simple wrapper with simple after modifier 450% slower
2102 simple wrapper with simple around modifier 500-550% slower
2103 simple wrapper with all 3 modifiers 1100% slower
2105 These numbers may seem daunting, but you must remember, every feature
2106 comes with some cost. To put things in perspective, just doing a
2107 simple C<AUTOLOAD> which does nothing but extract the name of the
2108 method called and return it costs about 400% over a normal method
2113 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
2115 This wraps the specified method with the supplied subroutine
2116 reference. The modifier will be called as a method itself, and will
2117 receive the same arguments as are passed to the method.
2119 When the modifier exits, the wrapped method will be called.
2121 The return value of the modifier will be ignored.
2123 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
2125 This wraps the specified method with the supplied subroutine
2126 reference. The modifier will be called as a method itself, and will
2127 receive the same arguments as are passed to the method.
2129 When the wrapped methods exits, the modifier will be called.
2131 The return value of the modifier will be ignored.
2133 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
2135 This wraps the specified method with the supplied subroutine
2138 The first argument passed to the modifier will be a subroutine
2139 reference to the wrapped method. The second argument is the object,
2140 and after that come any arguments passed when the method is called.
2142 The around modifier can choose to call the original method, as well as
2143 what arguments to pass if it does so.
2145 The return value of the modifier is what will be seen by the caller.
2149 =head2 Introspection
2153 =item B<< Class::MOP::Class->meta >>
2155 This will return a L<Class::MOP::Class> instance for this class.
2157 It should also be noted that L<Class::MOP> will actually bootstrap
2158 this module by installing a number of attribute meta-objects into its