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;
13 use Scalar::Util 'blessed', 'reftype', 'weaken';
14 use Sub::Name 'subname';
15 use Devel::GlobalDestruction 'in_global_destruction';
18 our $VERSION = '1.01';
19 $VERSION = eval $VERSION;
20 our $AUTHORITY = 'cpan:STEVAN';
22 use base 'Class::MOP::Module', 'Class::MOP::Mixin::HasAttributes';
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, @_);
45 # NOTE: (meta-circularity)
46 # this is a special form of _construct_instance
47 # (see below), which is used to construct class
48 # meta-object instances for any Class::MOP::*
49 # class. All other classes will use the more
50 # normal &construct_instance.
51 sub _construct_class_instance {
53 my $options = @_ == 1 ? $_[0] : {@_};
54 my $package_name = $options->{package};
55 (defined $package_name && $package_name)
56 || confess "You must pass a package name";
58 # return the metaclass if we have it cached,
59 # and it is still defined (it has not been
60 # reaped by DESTROY yet, which can happen
61 # annoyingly enough during global destruction)
63 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
68 # we need to deal with the possibility
69 # of class immutability here, and then
70 # get the name of the class appropriately
72 ? ($class->is_immutable
73 ? $class->_get_mutable_metaclass_name()
77 # now create the metaclass
79 if ($class eq 'Class::MOP::Class') {
80 $meta = $class->_new($options);
84 # it is safe to use meta here because
85 # class will always be a subclass of
86 # Class::MOP::Class, which defines meta
87 $meta = $class->meta->_construct_instance($options)
90 # and check the metaclass compatibility
91 $meta->_check_metaclass_compatibility();
93 Class::MOP::store_metaclass_by_name($package_name, $meta);
96 # we need to weaken any anon classes
97 # so that they can call DESTROY properly
98 Class::MOP::weaken_metaclass($package_name) if $meta->is_anon_class;
106 return Class::MOP::Class->initialize($class)->new_object(@_)
107 if $class ne __PACKAGE__;
109 my $options = @_ == 1 ? $_[0] : {@_};
112 # inherited from Class::MOP::Package
113 'package' => $options->{package},
116 # since the following attributes will
117 # actually be loaded from the symbol
118 # table, and actually bypass the instance
119 # entirely, we can just leave these things
120 # listed here for reference, because they
121 # should not actually have a value associated
123 'namespace' => \undef,
126 # inherited from Class::MOP::Module
128 'authority' => \undef,
130 # defined in Class::MOP::Class
131 'superclasses' => \undef,
134 'attribute_metaclass' =>
135 ( $options->{'attribute_metaclass'} || 'Class::MOP::Attribute' ),
136 'method_metaclass' =>
137 ( $options->{'method_metaclass'} || 'Class::MOP::Method' ),
138 'wrapped_method_metaclass' => (
139 $options->{'wrapped_method_metaclass'}
140 || 'Class::MOP::Method::Wrapped'
142 'instance_metaclass' =>
143 ( $options->{'instance_metaclass'} || 'Class::MOP::Instance' ),
144 'immutable_trait' => (
145 $options->{'immutable_trait'}
146 || 'Class::MOP::Class::Immutable::Trait'
148 'constructor_name' => ( $options->{constructor_name} || 'new' ),
149 'constructor_class' => (
150 $options->{constructor_class} || 'Class::MOP::Method::Constructor'
152 'destructor_class' => $options->{destructor_class},
156 sub reset_package_cache_flag { (shift)->{'_package_cache_flag'} = undef }
157 sub update_package_cache_flag {
160 # we can manually update the cache number
161 # since we are actually adding the method
162 # to our cache as well. This avoids us
163 # having to regenerate the method_map.
165 $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
168 sub _check_metaclass_compatibility {
171 # this is always okay ...
172 return if ref($self) eq 'Class::MOP::Class' &&
173 $self->instance_metaclass eq 'Class::MOP::Instance';
175 my @class_list = $self->linearized_isa;
176 shift @class_list; # shift off $self->name
178 foreach my $superclass_name (@class_list) {
179 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name) || next;
182 # we need to deal with the possibility
183 # of class immutability here, and then
184 # get the name of the class appropriately
186 = $super_meta->is_immutable
187 ? $super_meta->_get_mutable_metaclass_name()
190 ($self->isa($super_meta_type))
191 || confess "The metaclass of " . $self->name . " ("
192 . (ref($self)) . ")" . " is not compatible with the " .
193 "metaclass of its superclass, ".$superclass_name . " ("
194 . ($super_meta_type) . ")";
196 # we also need to check that instance metaclasses
197 # are compatibile in the same the class.
198 ($self->instance_metaclass->isa($super_meta->instance_metaclass))
199 || confess "The instance metaclass for " . $self->name . " (" . ($self->instance_metaclass) . ")" .
200 " is not compatible with the " .
201 "instance metaclass of its superclass, " . $superclass_name . " (" . ($super_meta->instance_metaclass) . ")";
209 # this should be sufficient, if you have a
210 # use case where it is not, write a test and
212 my $ANON_CLASS_SERIAL = 0;
215 # we need a sufficiently annoying prefix
216 # this should suffice for now, this is
217 # used in a couple of places below, so
218 # need to put it up here for now.
219 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
223 no warnings 'uninitialized';
224 $self->name =~ /^$ANON_CLASS_PREFIX/o;
227 sub create_anon_class {
228 my ($class, %options) = @_;
229 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
230 return $class->create($package_name, %options);
234 # this will only get called for
235 # anon-classes, all other calls
236 # are assumed to occur during
237 # global destruction and so don't
238 # really need to be handled explicitly
242 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
244 no warnings 'uninitialized';
245 my $name = $self->name;
246 return unless $name =~ /^$ANON_CLASS_PREFIX/o;
248 # Moose does a weird thing where it replaces the metaclass for
249 # class when fixing metaclass incompatibility. In that case,
250 # we don't want to clean out the namespace now. We can detect
251 # that because Moose will explicitly update the singleton
252 # cache in Class::MOP.
253 my $current_meta = Class::MOP::get_metaclass_by_name($name);
254 return if $current_meta ne $self;
256 my ($serial_id) = ($name =~ /^$ANON_CLASS_PREFIX(\d+)/o);
258 @{$name . '::ISA'} = ();
259 %{$name . '::'} = ();
260 delete ${$ANON_CLASS_PREFIX}{$serial_id . '::'};
262 Class::MOP::remove_metaclass_by_name($name);
267 # creating classes with MOP ...
270 my ( $class, @args ) = @_;
272 unshift @args, 'package' if @args % 2 == 1;
274 my (%options) = @args;
275 my $package_name = $options{package};
277 (ref $options{superclasses} eq 'ARRAY')
278 || confess "You must pass an ARRAY ref of superclasses"
279 if exists $options{superclasses};
281 (ref $options{attributes} eq 'ARRAY')
282 || confess "You must pass an ARRAY ref of attributes"
283 if exists $options{attributes};
285 (ref $options{methods} eq 'HASH')
286 || confess "You must pass a HASH ref of methods"
287 if exists $options{methods};
289 my (%initialize_options) = @args;
290 delete @initialize_options{qw(
298 my $meta = $class->initialize( $package_name => %initialize_options );
300 $meta->_instantiate_module( $options{version}, $options{authority} );
303 $meta->add_method('meta' => sub {
304 $class->initialize(ref($_[0]) || $_[0]);
307 $meta->superclasses(@{$options{superclasses}})
308 if exists $options{superclasses};
310 # process attributes first, so that they can
311 # install accessors, but locally defined methods
312 # can then overwrite them. It is maybe a little odd, but
313 # I think this should be the order of things.
314 if (exists $options{attributes}) {
315 foreach my $attr (@{$options{attributes}}) {
316 $meta->add_attribute($attr);
319 if (exists $options{methods}) {
320 foreach my $method_name (keys %{$options{methods}}) {
321 $meta->add_method($method_name, $options{methods}->{$method_name});
330 # all these attribute readers will be bootstrapped
331 # away in the Class::MOP bootstrap section
333 sub instance_metaclass { $_[0]->{'instance_metaclass'} }
334 sub immutable_trait { $_[0]->{'immutable_trait'} }
335 sub constructor_class { $_[0]->{'constructor_class'} }
336 sub constructor_name { $_[0]->{'constructor_name'} }
337 sub destructor_class { $_[0]->{'destructor_class'} }
339 # Instance Construction & Cloning
345 # we need to protect the integrity of the
346 # Class::MOP::Class singletons here, so we
347 # delegate this to &construct_class_instance
348 # which will deal with the singletons
349 return $class->_construct_class_instance(@_)
350 if $class->name->isa('Class::MOP::Class');
351 return $class->_construct_instance(@_);
354 sub _construct_instance {
356 my $params = @_ == 1 ? $_[0] : {@_};
357 my $meta_instance = $class->get_meta_instance();
359 # the code below is almost certainly incorrect
360 # but this is foreign inheritance, so we might
361 # have to kludge it in the end.
363 if (my $instance_class = blessed($params->{__INSTANCE__})) {
364 ($instance_class eq $class->name)
365 || confess "Objects passed as the __INSTANCE__ parameter must "
366 . "already be blessed into the correct class, but "
367 . "$params->{__INSTANCE__} is not a " . $class->name;
368 $instance = $params->{__INSTANCE__};
370 elsif (exists $params->{__INSTANCE__}) {
371 confess "The __INSTANCE__ parameter must be a blessed reference, not "
372 . $params->{__INSTANCE__};
375 $instance = $meta_instance->create_instance();
377 foreach my $attr ($class->get_all_attributes()) {
378 $attr->initialize_instance_slot($meta_instance, $instance, $params);
381 # this will only work for a HASH instance type
382 if ($class->is_anon_class) {
383 (reftype($instance) eq 'HASH')
384 || confess "Currently only HASH based instances are supported with instance of anon-classes";
386 # At some point we should make this official
387 # as a reserved slot name, but right now I am
388 # going to keep it here.
389 # my $RESERVED_MOP_SLOT = '__MOP__';
390 $instance->{'__MOP__'} = $class;
396 sub get_meta_instance {
398 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
401 sub _create_meta_instance {
404 my $instance = $self->instance_metaclass->new(
405 associated_metaclass => $self,
406 attributes => [ $self->get_all_attributes() ],
409 $self->add_meta_instance_dependencies()
410 if $instance->is_dependent_on_superclasses();
417 my $instance = shift;
418 (blessed($instance) && $instance->isa($class->name))
419 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
422 # we need to protect the integrity of the
423 # Class::MOP::Class singletons here, they
424 # should not be cloned.
425 return $instance if $instance->isa('Class::MOP::Class');
426 $class->_clone_instance($instance, @_);
429 sub _clone_instance {
430 my ($class, $instance, %params) = @_;
432 || confess "You can only clone instances, ($instance) is not a blessed instance";
433 my $meta_instance = $class->get_meta_instance();
434 my $clone = $meta_instance->clone_instance($instance);
435 foreach my $attr ($class->get_all_attributes()) {
436 if ( defined( my $init_arg = $attr->init_arg ) ) {
437 if (exists $params{$init_arg}) {
438 $attr->set_value($clone, $params{$init_arg});
445 sub rebless_instance {
446 my ($self, $instance, %params) = @_;
448 my $old_metaclass = Class::MOP::class_of($instance);
450 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
451 $self->name->isa($old_class)
452 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
454 $old_metaclass->rebless_instance_away($instance, $self, %params)
457 my $meta_instance = $self->get_meta_instance();
460 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
461 $meta_instance->rebless_instance_structure($_[1], $self);
463 foreach my $attr ( $self->get_all_attributes ) {
464 if ( $attr->has_value($instance) ) {
465 if ( defined( my $init_arg = $attr->init_arg ) ) {
466 $params{$init_arg} = $attr->get_value($instance)
467 unless exists $params{$init_arg};
470 $attr->set_value($instance, $attr->get_value($instance));
475 foreach my $attr ($self->get_all_attributes) {
476 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
482 sub rebless_instance_back {
483 my ( $self, $instance ) = @_;
485 my $old_metaclass = Class::MOP::class_of($instance);
488 = $old_metaclass ? $old_metaclass->name : blessed($instance);
489 $old_class->isa( $self->name )
491 "You may rebless only into a superclass of ($old_class), of which ("
495 $old_metaclass->rebless_instance_away( $instance, $self )
498 my $meta_instance = $self->get_meta_instance;
500 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
501 $meta_instance->rebless_instance_structure( $_[1], $self );
503 for my $attr ( $old_metaclass->get_all_attributes ) {
504 next if $self->has_attribute( $attr->name );
505 $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
511 sub rebless_instance_away {
512 # this intentionally does nothing, it is just a hook
515 sub _attach_attribute {
516 my ($self, $attribute) = @_;
517 $attribute->attach_to_class($self);
520 sub _post_add_attribute {
521 my ( $self, $attribute ) = @_;
523 $self->invalidate_meta_instances;
525 # invalidate package flag here
528 $attribute->install_accessors;
531 $self->remove_attribute( $attribute->name );
536 sub remove_attribute {
539 my $removed_attribute = $self->SUPER::remove_attribute(@_)
542 $self->invalidate_meta_instances;
544 $removed_attribute->remove_accessors;
545 $removed_attribute->detach_from_class;
547 return$removed_attribute;
550 sub find_attribute_by_name {
551 my ( $self, $attr_name ) = @_;
553 foreach my $class ( $self->linearized_isa ) {
554 # fetch the meta-class ...
555 my $meta = $self->initialize($class);
556 return $meta->get_attribute($attr_name)
557 if $meta->has_attribute($attr_name);
563 sub get_all_attributes {
565 my %attrs = map { %{ $self->initialize($_)->_attribute_map } }
566 reverse $self->linearized_isa;
567 return values %attrs;
574 my $var_spec = { sigil => '@', type => 'ARRAY', name => 'ISA' };
577 @{$self->get_package_symbol($var_spec)} = @supers;
580 # on 5.8 and below, we need to call
581 # a method to get Perl to detect
582 # a cycle in the class hierarchy
583 my $class = $self->name;
587 # we need to check the metaclass
588 # compatibility here so that we can
589 # be sure that the superclass is
590 # not potentially creating an issues
591 # we don't know about
593 $self->_check_metaclass_compatibility();
594 $self->_superclasses_updated();
596 @{$self->get_package_symbol($var_spec)};
599 sub _superclasses_updated {
601 $self->update_meta_instance_dependencies();
606 my $super_class = $self->name;
608 return @{ $super_class->mro::get_isarev() };
611 sub direct_subclasses {
613 my $super_class = $self->name;
618 } Class::MOP::Class->initialize($_)->superclasses
623 return @{ mro::get_linear_isa( (shift)->name ) };
626 sub class_precedence_list {
628 my $name = $self->name;
630 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
632 # We need to check for circular inheritance here
633 # if we are are not on 5.10, cause 5.8 detects it
634 # late. This will do nothing if all is well, and
635 # blow up otherwise. Yes, it's an ugly hack, better
636 # suggestions are welcome.
638 ($name || return)->isa('This is a test for circular inheritance')
641 # if our mro is c3, we can
642 # just grab the linear_isa
643 if (mro::get_mro($name) eq 'c3') {
644 return @{ mro::get_linear_isa($name) }
648 # we can't grab the linear_isa for dfs
649 # since it has all the duplicates
654 $self->initialize($_)->class_precedence_list()
655 } $self->superclasses()
663 my $fetch_and_prepare_method = sub {
664 my ($self, $method_name) = @_;
665 my $wrapped_metaclass = $self->wrapped_method_metaclass;
667 my $method = $self->get_method($method_name);
668 # if we dont have local ...
670 # try to find the next method
671 $method = $self->find_next_method_by_name($method_name);
672 # die if it does not exist
674 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
675 # and now make sure to wrap it
676 # even if it is already wrapped
677 # because we need a new sub ref
678 $method = $wrapped_metaclass->wrap($method,
679 package_name => $self->name,
680 name => $method_name,
684 # now make sure we wrap it properly
685 $method = $wrapped_metaclass->wrap($method,
686 package_name => $self->name,
687 name => $method_name,
688 ) unless $method->isa($wrapped_metaclass);
690 $self->add_method($method_name => $method);
694 sub add_before_method_modifier {
695 my ($self, $method_name, $method_modifier) = @_;
696 (defined $method_name && length $method_name)
697 || confess "You must pass in a method name";
698 my $method = $fetch_and_prepare_method->($self, $method_name);
699 $method->add_before_modifier(
700 subname(':before' => $method_modifier)
704 sub add_after_method_modifier {
705 my ($self, $method_name, $method_modifier) = @_;
706 (defined $method_name && length $method_name)
707 || confess "You must pass in a method name";
708 my $method = $fetch_and_prepare_method->($self, $method_name);
709 $method->add_after_modifier(
710 subname(':after' => $method_modifier)
714 sub add_around_method_modifier {
715 my ($self, $method_name, $method_modifier) = @_;
716 (defined $method_name && length $method_name)
717 || confess "You must pass in a method name";
718 my $method = $fetch_and_prepare_method->($self, $method_name);
719 $method->add_around_modifier(
720 subname(':around' => $method_modifier)
725 # the methods above used to be named like this:
726 # ${pkg}::${method}:(before|after|around)
727 # but this proved problematic when using one modifier
728 # to wrap multiple methods (something which is likely
729 # to happen pretty regularly IMO). So instead of naming
730 # it like this, I have chosen to just name them purely
731 # with their modifier names, like so:
732 # :(before|after|around)
733 # The fact is that in a stack trace, it will be fairly
734 # evident from the context what method they are attached
735 # to, and so don't need the fully qualified name.
738 sub find_method_by_name {
739 my ($self, $method_name) = @_;
740 (defined $method_name && length $method_name)
741 || confess "You must define a method name to find";
742 foreach my $class ($self->linearized_isa) {
743 my $method = $self->initialize($class)->get_method($method_name);
744 return $method if defined $method;
749 sub get_all_methods {
753 for my $class ( reverse $self->linearized_isa ) {
754 my $meta = $self->initialize($class);
756 $methods{$_} = $meta->get_method($_)
757 for $meta->get_method_list;
760 return values %methods;
763 sub get_all_method_names {
766 return grep { !$uniq{$_}++ } map { $self->initialize($_)->get_method_list } $self->linearized_isa;
769 sub find_all_methods_by_name {
770 my ($self, $method_name) = @_;
771 (defined $method_name && length $method_name)
772 || confess "You must define a method name to find";
774 foreach my $class ($self->linearized_isa) {
775 # fetch the meta-class ...
776 my $meta = $self->initialize($class);
778 name => $method_name,
780 code => $meta->get_method($method_name)
781 } if $meta->has_method($method_name);
786 sub find_next_method_by_name {
787 my ($self, $method_name) = @_;
788 (defined $method_name && length $method_name)
789 || confess "You must define a method name to find";
790 my @cpl = $self->linearized_isa;
791 shift @cpl; # discard ourselves
792 foreach my $class (@cpl) {
793 my $method = $self->initialize($class)->get_method($method_name);
794 return $method if defined $method;
799 sub update_meta_instance_dependencies {
802 if ( $self->{meta_instance_dependencies} ) {
803 return $self->add_meta_instance_dependencies;
807 sub add_meta_instance_dependencies {
810 $self->remove_meta_instance_dependencies;
812 my @attrs = $self->get_all_attributes();
815 my @classes = grep { not $seen{ $_->name }++ }
816 map { $_->associated_class } @attrs;
818 foreach my $class (@classes) {
819 $class->add_dependent_meta_instance($self);
822 $self->{meta_instance_dependencies} = \@classes;
825 sub remove_meta_instance_dependencies {
828 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
829 foreach my $class (@$classes) {
830 $class->remove_dependent_meta_instance($self);
840 sub add_dependent_meta_instance {
841 my ( $self, $metaclass ) = @_;
842 push @{ $self->{dependent_meta_instances} }, $metaclass;
845 sub remove_dependent_meta_instance {
846 my ( $self, $metaclass ) = @_;
847 my $name = $metaclass->name;
848 @$_ = grep { $_->name ne $name } @$_
849 for $self->{dependent_meta_instances};
852 sub invalidate_meta_instances {
854 $_->invalidate_meta_instance()
855 for $self, @{ $self->{dependent_meta_instances} };
858 sub invalidate_meta_instance {
860 undef $self->{_meta_instance};
863 # check if we can reinitialize
867 # if any local attr is defined
868 return if $self->get_attribute_list;
870 # or any non-declared methods
871 for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
872 return if $method->isa("Class::MOP::Method::Generated");
873 # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
882 sub is_immutable { 0 }
884 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
886 sub _immutable_options {
887 my ( $self, @args ) = @_;
890 inline_accessors => 1,
891 inline_constructor => 1,
892 inline_destructor => 0,
894 immutable_trait => $self->immutable_trait,
895 constructor_name => $self->constructor_name,
896 constructor_class => $self->constructor_class,
897 destructor_class => $self->destructor_class,
903 my ( $self, @args ) = @_;
905 if ( $self->is_mutable ) {
906 $self->_initialize_immutable( $self->_immutable_options(@args) );
907 $self->_rebless_as_immutable(@args);
918 if ( $self->is_immutable ) {
919 my @args = $self->immutable_options;
920 $self->_rebless_as_mutable();
921 $self->_remove_inlined_code(@args);
922 delete $self->{__immutable};
930 sub _rebless_as_immutable {
931 my ( $self, @args ) = @_;
933 $self->{__immutable}{original_class} = ref $self;
935 bless $self => $self->_immutable_metaclass(@args);
938 sub _immutable_metaclass {
939 my ( $self, %args ) = @_;
941 if ( my $class = $args{immutable_metaclass} ) {
945 my $trait = $args{immutable_trait} = $self->immutable_trait
946 || confess "no immutable trait specified for $self";
948 my $meta = $self->meta;
949 my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
953 if ( $meta_attr and $trait eq $meta_attr->default ) {
954 # if the trait is the same as the default we try and pick a
955 # predictable name for the immutable metaclass
956 $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
959 $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
960 $trait, 'ForMetaClass', ref($self);
964 if Class::MOP::is_class_loaded($class_name);
966 # If the metaclass is a subclass of CMOP::Class which has had
967 # metaclass roles applied (via Moose), then we want to make sure
968 # that we preserve that anonymous class (see Fey::ORM for an
969 # example of where this matters).
971 = $meta->is_immutable
972 ? $meta->_get_mutable_metaclass_name
975 my $immutable_meta = $meta_name->create(
977 superclasses => [ ref $self ],
980 Class::MOP::load_class($trait);
981 for my $meth ( Class::MOP::Class->initialize($trait)->get_all_methods ) {
982 my $meth_name = $meth->name;
984 if ( $immutable_meta->find_method_by_name( $meth_name ) ) {
985 $immutable_meta->add_around_method_modifier( $meth_name, $meth->body );
988 $immutable_meta->add_method( $meth_name, $meth->clone );
992 $immutable_meta->make_immutable(
993 inline_constructor => 0,
994 inline_accessors => 0,
1000 sub _remove_inlined_code {
1003 $self->remove_method( $_->name ) for $self->_inlined_methods;
1005 delete $self->{__immutable}{inlined_methods};
1008 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1010 sub _add_inlined_method {
1011 my ( $self, $method ) = @_;
1013 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1016 sub _initialize_immutable {
1017 my ( $self, %args ) = @_;
1019 $self->{__immutable}{options} = \%args;
1020 $self->_install_inlined_code(%args);
1023 sub _install_inlined_code {
1024 my ( $self, %args ) = @_;
1027 $self->_inline_accessors(%args) if $args{inline_accessors};
1028 $self->_inline_constructor(%args) if $args{inline_constructor};
1029 $self->_inline_destructor(%args) if $args{inline_destructor};
1032 sub _rebless_as_mutable {
1035 bless $self, $self->_get_mutable_metaclass_name;
1040 sub _inline_accessors {
1043 foreach my $attr_name ( $self->get_attribute_list ) {
1044 $self->get_attribute($attr_name)->install_accessors(1);
1048 sub _inline_constructor {
1049 my ( $self, %args ) = @_;
1051 my $name = $args{constructor_name};
1052 # A class may not even have a constructor, and that's okay.
1053 return unless defined $name;
1055 if ( $self->has_method($name) && !$args{replace_constructor} ) {
1056 my $class = $self->name;
1057 warn "Not inlining a constructor for $class since it defines"
1058 . " its own constructor.\n"
1059 . "If you are certain you don't need to inline your"
1060 . " constructor, specify inline_constructor => 0 in your"
1061 . " call to $class->meta->make_immutable\n";
1065 my $constructor_class = $args{constructor_class};
1067 Class::MOP::load_class($constructor_class);
1069 my $constructor = $constructor_class->new(
1073 package_name => $self->name,
1077 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1078 $self->add_method( $name => $constructor );
1079 $self->_add_inlined_method($constructor);
1083 sub _inline_destructor {
1084 my ( $self, %args ) = @_;
1086 ( exists $args{destructor_class} && defined $args{destructor_class} )
1087 || confess "The 'inline_destructor' option is present, but "
1088 . "no destructor class was specified";
1090 if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1091 my $class = $self->name;
1092 warn "Not inlining a destructor for $class since it defines"
1093 . " its own destructor.\n";
1097 my $destructor_class = $args{destructor_class};
1099 Class::MOP::load_class($destructor_class);
1101 return unless $destructor_class->is_needed($self);
1103 my $destructor = $destructor_class->new(
1106 package_name => $self->name,
1110 if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1111 $self->add_method( 'DESTROY' => $destructor );
1112 $self->_add_inlined_method($destructor);
1124 Class::MOP::Class - Class Meta Object
1128 # assuming that class Foo
1129 # has been defined, you can
1131 # use this for introspection ...
1133 # add a method to Foo ...
1134 Foo->meta->add_method( 'bar' => sub {...} )
1136 # get a list of all the classes searched
1137 # the method dispatcher in the correct order
1138 Foo->meta->class_precedence_list()
1140 # remove a method from Foo
1141 Foo->meta->remove_method('bar');
1143 # or use this to actually create classes ...
1145 Class::MOP::Class->create(
1148 superclasses => ['Foo'],
1150 Class::MOP::Attribute->new('$bar'),
1151 Class::MOP::Attribute->new('$baz'),
1154 calculate_bar => sub {...},
1155 construct_baz => sub {...}
1162 The Class Protocol is the largest and most complex part of the
1163 Class::MOP meta-object protocol. It controls the introspection and
1164 manipulation of Perl 5 classes, and it can create them as well. The
1165 best way to understand what this module can do is to read the
1166 documentation for each of its methods.
1170 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1174 =head2 Class construction
1176 These methods all create new C<Class::MOP::Class> objects. These
1177 objects can represent existing classes or they can be used to create
1178 new classes from scratch.
1180 The metaclass object for a given class is a singleton. If you attempt
1181 to create a metaclass for the same class twice, you will just get the
1186 =item B<< Class::MOP::Class->create($package_name, %options) >>
1188 This method creates a new C<Class::MOP::Class> object with the given
1189 package name. It accepts a number of options:
1195 An optional version number for the newly created package.
1199 An optional authority for the newly created package.
1201 =item * superclasses
1203 An optional array reference of superclass names.
1207 An optional hash reference of methods for the class. The keys of the
1208 hash reference are method names and values are subroutine references.
1212 An optional array reference of L<Class::MOP::Attribute> objects.
1216 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1218 This method works just like C<< Class::MOP::Class->create >> but it
1219 creates an "anonymous" class. In fact, the class does have a name, but
1220 that name is a unique name generated internally by this module.
1222 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1223 parameters that C<create> accepts.
1225 Anonymous classes are destroyed once the metaclass they are attached
1226 to goes out of scope, and will be removed from Perl's internal symbol
1229 All instances of an anonymous class keep a special reference to the
1230 metaclass object, which prevents the metaclass from going out of scope
1231 while any instances exist.
1233 This only works if the instance is based on a hash reference, however.
1235 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1237 This method will initialize a C<Class::MOP::Class> object for the
1238 named package. Unlike C<create>, this method I<will not> create a new
1241 The purpose of this method is to retrieve a C<Class::MOP::Class>
1242 object for introspecting an existing class.
1244 If an existing C<Class::MOP::Class> object exists for the named
1245 package, it will be returned, and any options provided will be
1248 If the object does not yet exist, it will be created.
1250 The valid options that can be passed to this method are
1251 C<attribute_metaclass>, C<method_metaclass>,
1252 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1253 optional, and default to the appropriate class in the C<Class::MOP>
1258 =head2 Object instance construction and cloning
1260 These methods are all related to creating and/or cloning object
1265 =item B<< $metaclass->clone_object($instance, %params) >>
1267 This method clones an existing object instance. Any parameters you
1268 provide are will override existing attribute values in the object.
1270 This is a convenience method for cloning an object instance, then
1271 blessing it into the appropriate package.
1273 You could implement a clone method in your class, using this method:
1276 my ($self, %params) = @_;
1277 $self->meta->clone_object($self, %params);
1280 =item B<< $metaclass->rebless_instance($instance, %params) >>
1282 This method changes the class of C<$instance> to the metaclass's class.
1284 You can only rebless an instance into a subclass of its current
1285 class. If you pass any additional parameters, these will be treated
1286 like constructor parameters and used to initialize the object's
1287 attributes. Any existing attributes that are already set will be
1290 Before reblessing the instance, this method will call
1291 C<rebless_instance_away> on the instance's current metaclass. This method
1292 will be passed the instance, the new metaclass, and any parameters
1293 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1294 does nothing; it is merely a hook.
1296 =item B<< $metaclass->rebless_instance_back($instance) >>
1298 Does the same thing as C<rebless_instance>, except that you can only
1299 rebless an instance into one of its superclasses. Any attributes that
1300 do not exist in the superclass will be deinitialized.
1302 This is a much more dangerous operation than C<rebless_instance>,
1303 especially when multiple inheritance is involved, so use this carefully!
1305 =item B<< $metaclass->new_object(%params) >>
1307 This method is used to create a new object of the metaclass's
1308 class. Any parameters you provide are used to initialize the
1309 instance's attributes. A special C<__INSTANCE__> key can be passed to
1310 provide an already generated instance, rather than having Class::MOP
1311 generate it for you. This is mostly useful for using Class::MOP with
1312 foreign classes which generate instances using their own constructors.
1314 =item B<< $metaclass->instance_metaclass >>
1316 Returns the class name of the instance metaclass. See
1317 L<Class::MOP::Instance> for more information on the instance
1320 =item B<< $metaclass->get_meta_instance >>
1322 Returns an instance of the C<instance_metaclass> to be used in the
1323 construction of a new instance of the class.
1327 =head2 Informational predicates
1329 These are a few predicate methods for asking information about the
1334 =item B<< $metaclass->is_anon_class >>
1336 This returns true if the class was created by calling C<<
1337 Class::MOP::Class->create_anon_class >>.
1339 =item B<< $metaclass->is_mutable >>
1341 This returns true if the class is still mutable.
1343 =item B<< $metaclass->is_immutable >>
1345 This returns true if the class has been made immutable.
1347 =item B<< $metaclass->is_pristine >>
1349 A class is I<not> pristine if it has non-inherited attributes or if it
1350 has any generated methods.
1354 =head2 Inheritance Relationships
1358 =item B<< $metaclass->superclasses(@superclasses) >>
1360 This is a read-write accessor which represents the superclass
1361 relationships of the metaclass's class.
1363 This is basically sugar around getting and setting C<@ISA>.
1365 =item B<< $metaclass->class_precedence_list >>
1367 This returns a list of all of the class's ancestor classes. The
1368 classes are returned in method dispatch order.
1370 =item B<< $metaclass->linearized_isa >>
1372 This returns a list based on C<class_precedence_list> but with all
1375 =item B<< $metaclass->subclasses >>
1377 This returns a list of all subclasses for this class, even indirect
1380 =item B<< $metaclass->direct_subclasses >>
1382 This returns a list of immediate subclasses for this class, which does not
1383 include indirect subclasses.
1387 =head2 Method introspection
1389 See L<Class::MOP::Package/Method introspection and creation> for
1390 methods that operate only on the current class. Class::MOP::Class adds
1391 introspection capabilities that take inheritance into account.
1395 =item B<< $metaclass->get_all_methods >>
1397 This will traverse the inheritance hierarchy and return a list of all
1398 the L<Class::MOP::Method> objects for this class and its parents.
1400 =item B<< $metaclass->find_method_by_name($method_name) >>
1402 This will return a L<Class::MOP::Method> for the specified
1403 C<$method_name>. If the class does not have the specified method, it
1406 Unlike C<get_method>, this method I<will> look for the named method in
1409 =item B<< $metaclass->get_all_method_names >>
1411 This will return a list of method I<names> for all of this class's
1412 methods, including inherited methods.
1414 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1416 This method looks for the named method in the class and all of its
1417 parents. It returns every matching method it finds in the inheritance
1418 tree, so it returns a list of methods.
1420 Each method is returned as a hash reference with three keys. The keys
1421 are C<name>, C<class>, and C<code>. The C<code> key has a
1422 L<Class::MOP::Method> object as its value.
1424 The list of methods is distinct.
1426 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1428 This method returns the first method in any superclass matching the
1429 given name. It is effectively the method that C<SUPER::$method_name>
1434 =head2 Attribute introspection and creation
1436 Because Perl 5 does not have a core concept of attributes in classes,
1437 we can only return information about attributes which have been added
1438 via this class's methods. We cannot discover information about
1439 attributes which are defined in terms of "regular" Perl 5 methods.
1443 =item B<< $metaclass->get_attribute($attribute_name) >>
1445 This will return a L<Class::MOP::Attribute> for the specified
1446 C<$attribute_name>. If the class does not have the specified
1447 attribute, it returns C<undef>.
1449 NOTE that get_attribute does not search superclasses, for that you
1450 need to use C<find_attribute_by_name>.
1452 =item B<< $metaclass->has_attribute($attribute_name) >>
1454 Returns a boolean indicating whether or not the class defines the
1455 named attribute. It does not include attributes inherited from parent
1458 =item B<< $metaclass->get_attribute_list >>
1460 This will return a list of attributes I<names> for all attributes
1461 defined in this class.
1463 =item B<< $metaclass->get_all_attributes >>
1465 This will traverse the inheritance hierarchy and return a list of all
1466 the L<Class::MOP::Attribute> objects for this class and its parents.
1468 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1470 This will return a L<Class::MOP::Attribute> for the specified
1471 C<$attribute_name>. If the class does not have the specified
1472 attribute, it returns C<undef>.
1474 Unlike C<get_attribute>, this attribute I<will> look for the named
1475 attribute in superclasses.
1477 =item B<< $metaclass->add_attribute(...) >>
1479 This method accepts either an existing L<Class::MOP::Attribute>
1480 object or parameters suitable for passing to that class's C<new>
1483 The attribute provided will be added to the class.
1485 Any accessor methods defined by the attribute will be added to the
1486 class when the attribute is added.
1488 If an attribute of the same name already exists, the old attribute
1489 will be removed first.
1491 =item B<< $metaclass->remove_attribute($attribute_name) >>
1493 This will remove the named attribute from the class, and
1494 L<Class::MOP::Attribute> object.
1496 Removing an attribute also removes any accessor methods defined by the
1499 However, note that removing an attribute will only affect I<future>
1500 object instances created for this class, not existing instances.
1502 =item B<< $metaclass->attribute_metaclass >>
1504 Returns the class name of the attribute metaclass for this class. By
1505 default, this is L<Class::MOP::Attribute>.
1509 =head2 Class Immutability
1511 Making a class immutable "freezes" the class definition. You can no
1512 longer call methods which alter the class, such as adding or removing
1513 methods or attributes.
1515 Making a class immutable lets us optimize the class by inlining some
1516 methods, and also allows us to optimize some methods on the metaclass
1519 After immutabilization, the metaclass object will cache most informational
1520 methods that returns information about methods or attributes. Methods which
1521 would alter the class, such as C<add_attribute> and C<add_method>, will
1522 throw an error on an immutable metaclass object.
1524 The immutabilization system in L<Moose> takes much greater advantage
1525 of the inlining features than Class::MOP itself does.
1529 =item B<< $metaclass->make_immutable(%options) >>
1531 This method will create an immutable transformer and use it to make
1532 the class and its metaclass object immutable.
1534 This method accepts the following options:
1538 =item * inline_accessors
1540 =item * inline_constructor
1542 =item * inline_destructor
1544 These are all booleans indicating whether the specified method(s)
1547 By default, accessors and the constructor are inlined, but not the
1550 =item * immutable_trait
1552 The name of a class which will be used as a parent class for the
1553 metaclass object being made immutable. This "trait" implements the
1554 post-immutability functionality of the metaclass (but not the
1555 transformation itself).
1557 This defaults to L<Class::MOP::Class::Immutable::Trait>.
1559 =item * constructor_name
1561 This is the constructor method name. This defaults to "new".
1563 =item * constructor_class
1565 The name of the method metaclass for constructors. It will be used to
1566 generate the inlined constructor. This defaults to
1567 "Class::MOP::Method::Constructor".
1569 =item * replace_constructor
1571 This is a boolean indicating whether an existing constructor should be
1572 replaced when inlining a constructor. This defaults to false.
1574 =item * destructor_class
1576 The name of the method metaclass for destructors. It will be used to
1577 generate the inlined destructor. This defaults to
1578 "Class::MOP::Method::Denstructor".
1580 =item * replace_destructor
1582 This is a boolean indicating whether an existing destructor should be
1583 replaced when inlining a destructor. This defaults to false.
1587 =item B<< $metaclass->immutable_options >>
1589 Returns a hash of the options used when making the class immutable, including
1590 both defaults and anything supplied by the user in the call to C<<
1591 $metaclass->make_immutable >>. This is useful if you need to temporarily make
1592 a class mutable and then restore immutability as it was before.
1594 =item B<< $metaclass->make_mutable >>
1596 Calling this method reverse the immutabilization transformation.
1600 =head2 Method Modifiers
1602 Method modifiers are hooks which allow a method to be wrapped with
1603 I<before>, I<after> and I<around> method modifiers. Every time a
1604 method is called, its modifiers are also called.
1606 A class can modify its own methods, as well as methods defined in
1609 =head3 How method modifiers work?
1611 Method modifiers work by wrapping the original method and then
1612 replacing it in the class's symbol table. The wrappers will handle
1613 calling all the modifiers in the appropriate order and preserving the
1614 calling context for the original method.
1616 The return values of C<before> and C<after> modifiers are
1617 ignored. This is because their purpose is B<not> to filter the input
1618 and output of the primary method (this is done with an I<around>
1621 This may seem like an odd restriction to some, but doing this allows
1622 for simple code to be added at the beginning or end of a method call
1623 without altering the function of the wrapped method or placing any
1624 extra responsibility on the code of the modifier.
1626 Of course if you have more complex needs, you can use the C<around>
1627 modifier which allows you to change both the parameters passed to the
1628 wrapped method, as well as its return value.
1630 Before and around modifiers are called in last-defined-first-called
1631 order, while after modifiers are called in first-defined-first-called
1632 order. So the call tree might looks something like this:
1644 =head3 What is the performance impact?
1646 Of course there is a performance cost associated with method
1647 modifiers, but we have made every effort to make that cost directly
1648 proportional to the number of modifier features you use.
1650 The wrapping method does its best to B<only> do as much work as it
1651 absolutely needs to. In order to do this we have moved some of the
1652 performance costs to set-up time, where they are easier to amortize.
1654 All this said, our benchmarks have indicated the following:
1656 simple wrapper with no modifiers 100% slower
1657 simple wrapper with simple before modifier 400% slower
1658 simple wrapper with simple after modifier 450% slower
1659 simple wrapper with simple around modifier 500-550% slower
1660 simple wrapper with all 3 modifiers 1100% slower
1662 These numbers may seem daunting, but you must remember, every feature
1663 comes with some cost. To put things in perspective, just doing a
1664 simple C<AUTOLOAD> which does nothing but extract the name of the
1665 method called and return it costs about 400% over a normal method
1670 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
1672 This wraps the specified method with the supplied subroutine
1673 reference. The modifier will be called as a method itself, and will
1674 receive the same arguments as are passed to the method.
1676 When the modifier exits, the wrapped method will be called.
1678 The return value of the modifier will be ignored.
1680 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
1682 This wraps the specified method with the supplied subroutine
1683 reference. The modifier will be called as a method itself, and will
1684 receive the same arguments as are passed to the method.
1686 When the wrapped methods exits, the modifier will be called.
1688 The return value of the modifier will be ignored.
1690 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
1692 This wraps the specified method with the supplied subroutine
1695 The first argument passed to the modifier will be a subroutine
1696 reference to the wrapped method. The second argument is the object,
1697 and after that come any arguments passed when the method is called.
1699 The around modifier can choose to call the original method, as well as
1700 what arguments to pass if it does so.
1702 The return value of the modifier is what will be seen by the caller.
1706 =head2 Introspection
1710 =item B<< Class::MOP::Class->meta >>
1712 This will return a L<Class::MOP::Class> instance for this class.
1714 It should also be noted that L<Class::MOP> will actually bootstrap
1715 this module by installing a number of attribute meta-objects into its
1722 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1724 =head1 COPYRIGHT AND LICENSE
1726 Copyright 2006-2010 by Infinity Interactive, Inc.
1728 L<http://www.iinteractive.com>
1730 This library is free software; you can redistribute it and/or modify
1731 it under the same terms as Perl itself.