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 = '0.98';
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.
362 my $instance = $params->{__INSTANCE__} || $meta_instance->create_instance();
363 foreach my $attr ($class->get_all_attributes()) {
364 $attr->initialize_instance_slot($meta_instance, $instance, $params);
367 # this will only work for a HASH instance type
368 if ($class->is_anon_class) {
369 (reftype($instance) eq 'HASH')
370 || confess "Currently only HASH based instances are supported with instance of anon-classes";
372 # At some point we should make this official
373 # as a reserved slot name, but right now I am
374 # going to keep it here.
375 # my $RESERVED_MOP_SLOT = '__MOP__';
376 $instance->{'__MOP__'} = $class;
382 sub get_meta_instance {
384 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
387 sub _create_meta_instance {
390 my $instance = $self->instance_metaclass->new(
391 associated_metaclass => $self,
392 attributes => [ $self->get_all_attributes() ],
395 $self->add_meta_instance_dependencies()
396 if $instance->is_dependent_on_superclasses();
403 my $instance = shift;
404 (blessed($instance) && $instance->isa($class->name))
405 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
408 # we need to protect the integrity of the
409 # Class::MOP::Class singletons here, they
410 # should not be cloned.
411 return $instance if $instance->isa('Class::MOP::Class');
412 $class->_clone_instance($instance, @_);
415 sub _clone_instance {
416 my ($class, $instance, %params) = @_;
418 || confess "You can only clone instances, ($instance) is not a blessed instance";
419 my $meta_instance = $class->get_meta_instance();
420 my $clone = $meta_instance->clone_instance($instance);
421 foreach my $attr ($class->get_all_attributes()) {
422 if ( defined( my $init_arg = $attr->init_arg ) ) {
423 if (exists $params{$init_arg}) {
424 $attr->set_value($clone, $params{$init_arg});
431 sub rebless_instance {
432 my ($self, $instance, %params) = @_;
434 my $old_metaclass = Class::MOP::class_of($instance);
436 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
437 $self->name->isa($old_class)
438 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
440 $old_metaclass->rebless_instance_away($instance, $self, %params)
443 my $meta_instance = $self->get_meta_instance();
446 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
447 $meta_instance->rebless_instance_structure($_[1], $self);
449 foreach my $attr ( $self->get_all_attributes ) {
450 if ( $attr->has_value($instance) ) {
451 if ( defined( my $init_arg = $attr->init_arg ) ) {
452 $params{$init_arg} = $attr->get_value($instance)
453 unless exists $params{$init_arg};
456 $attr->set_value($instance, $attr->get_value($instance));
461 foreach my $attr ($self->get_all_attributes) {
462 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
468 sub rebless_instance_back {
469 my ( $self, $instance ) = @_;
471 my $old_metaclass = Class::MOP::class_of($instance);
474 = $old_metaclass ? $old_metaclass->name : blessed($instance);
475 $old_class->isa( $self->name )
477 "You may rebless only into a superclass of ($old_class), of which ("
481 $old_metaclass->rebless_instance_away( $instance, $self )
484 my $meta_instance = $self->get_meta_instance;
486 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
487 $meta_instance->rebless_instance_structure( $_[1], $self );
489 for my $attr ( $old_metaclass->get_all_attributes ) {
490 next if $self->has_attribute( $attr->name );
491 $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
497 sub rebless_instance_away {
498 # this intentionally does nothing, it is just a hook
501 sub _attach_attribute {
502 my ($self, $attribute) = @_;
503 $attribute->attach_to_class($self);
506 sub _post_add_attribute {
507 my ( $self, $attribute ) = @_;
509 $self->invalidate_meta_instances;
511 # invalidate package flag here
514 $attribute->install_accessors;
517 $self->remove_attribute( $attribute->name );
522 sub remove_attribute {
525 my $removed_attribute = $self->SUPER::remove_attribute(@_)
528 $self->invalidate_meta_instances;
530 $removed_attribute->remove_accessors;
531 $removed_attribute->detach_from_class;
533 return$removed_attribute;
536 sub find_attribute_by_name {
537 my ( $self, $attr_name ) = @_;
539 foreach my $class ( $self->linearized_isa ) {
540 # fetch the meta-class ...
541 my $meta = $self->initialize($class);
542 return $meta->get_attribute($attr_name)
543 if $meta->has_attribute($attr_name);
549 sub get_all_attributes {
551 my %attrs = map { %{ $self->initialize($_)->_attribute_map } }
552 reverse $self->linearized_isa;
553 return values %attrs;
560 my $var_spec = { sigil => '@', type => 'ARRAY', name => 'ISA' };
563 @{$self->get_package_symbol($var_spec)} = @supers;
566 # on 5.8 and below, we need to call
567 # a method to get Perl to detect
568 # a cycle in the class hierarchy
569 my $class = $self->name;
573 # we need to check the metaclass
574 # compatibility here so that we can
575 # be sure that the superclass is
576 # not potentially creating an issues
577 # we don't know about
579 $self->_check_metaclass_compatibility();
580 $self->_superclasses_updated();
582 @{$self->get_package_symbol($var_spec)};
585 sub _superclasses_updated {
587 $self->update_meta_instance_dependencies();
592 my $super_class = $self->name;
594 return @{ $super_class->mro::get_isarev() };
597 sub direct_subclasses {
599 my $super_class = $self->name;
604 } Class::MOP::Class->initialize($_)->superclasses
609 return @{ mro::get_linear_isa( (shift)->name ) };
612 sub class_precedence_list {
614 my $name = $self->name;
616 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
618 # We need to check for circular inheritance here
619 # if we are are not on 5.10, cause 5.8 detects it
620 # late. This will do nothing if all is well, and
621 # blow up otherwise. Yes, it's an ugly hack, better
622 # suggestions are welcome.
624 ($name || return)->isa('This is a test for circular inheritance')
627 # if our mro is c3, we can
628 # just grab the linear_isa
629 if (mro::get_mro($name) eq 'c3') {
630 return @{ mro::get_linear_isa($name) }
634 # we can't grab the linear_isa for dfs
635 # since it has all the duplicates
640 $self->initialize($_)->class_precedence_list()
641 } $self->superclasses()
649 my $fetch_and_prepare_method = sub {
650 my ($self, $method_name) = @_;
651 my $wrapped_metaclass = $self->wrapped_method_metaclass;
653 my $method = $self->get_method($method_name);
654 # if we dont have local ...
656 # try to find the next method
657 $method = $self->find_next_method_by_name($method_name);
658 # die if it does not exist
660 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
661 # and now make sure to wrap it
662 # even if it is already wrapped
663 # because we need a new sub ref
664 $method = $wrapped_metaclass->wrap($method,
665 package_name => $self->name,
666 name => $method_name,
670 # now make sure we wrap it properly
671 $method = $wrapped_metaclass->wrap($method,
672 package_name => $self->name,
673 name => $method_name,
674 ) unless $method->isa($wrapped_metaclass);
676 $self->add_method($method_name => $method);
680 sub add_before_method_modifier {
681 my ($self, $method_name, $method_modifier) = @_;
682 (defined $method_name && length $method_name)
683 || confess "You must pass in a method name";
684 my $method = $fetch_and_prepare_method->($self, $method_name);
685 $method->add_before_modifier(
686 subname(':before' => $method_modifier)
690 sub add_after_method_modifier {
691 my ($self, $method_name, $method_modifier) = @_;
692 (defined $method_name && length $method_name)
693 || confess "You must pass in a method name";
694 my $method = $fetch_and_prepare_method->($self, $method_name);
695 $method->add_after_modifier(
696 subname(':after' => $method_modifier)
700 sub add_around_method_modifier {
701 my ($self, $method_name, $method_modifier) = @_;
702 (defined $method_name && length $method_name)
703 || confess "You must pass in a method name";
704 my $method = $fetch_and_prepare_method->($self, $method_name);
705 $method->add_around_modifier(
706 subname(':around' => $method_modifier)
711 # the methods above used to be named like this:
712 # ${pkg}::${method}:(before|after|around)
713 # but this proved problematic when using one modifier
714 # to wrap multiple methods (something which is likely
715 # to happen pretty regularly IMO). So instead of naming
716 # it like this, I have chosen to just name them purely
717 # with their modifier names, like so:
718 # :(before|after|around)
719 # The fact is that in a stack trace, it will be fairly
720 # evident from the context what method they are attached
721 # to, and so don't need the fully qualified name.
724 sub find_method_by_name {
725 my ($self, $method_name) = @_;
726 (defined $method_name && length $method_name)
727 || confess "You must define a method name to find";
728 foreach my $class ($self->linearized_isa) {
729 my $method = $self->initialize($class)->get_method($method_name);
730 return $method if defined $method;
735 sub get_all_methods {
739 for my $class ( reverse $self->linearized_isa ) {
740 my $meta = $self->initialize($class);
742 $methods{$_} = $meta->get_method($_)
743 for $meta->get_method_list;
746 return values %methods;
749 sub get_all_method_names {
752 return grep { !$uniq{$_}++ } map { $self->initialize($_)->get_method_list } $self->linearized_isa;
755 sub find_all_methods_by_name {
756 my ($self, $method_name) = @_;
757 (defined $method_name && length $method_name)
758 || confess "You must define a method name to find";
760 foreach my $class ($self->linearized_isa) {
761 # fetch the meta-class ...
762 my $meta = $self->initialize($class);
764 name => $method_name,
766 code => $meta->get_method($method_name)
767 } if $meta->has_method($method_name);
772 sub find_next_method_by_name {
773 my ($self, $method_name) = @_;
774 (defined $method_name && length $method_name)
775 || confess "You must define a method name to find";
776 my @cpl = $self->linearized_isa;
777 shift @cpl; # discard ourselves
778 foreach my $class (@cpl) {
779 my $method = $self->initialize($class)->get_method($method_name);
780 return $method if defined $method;
785 sub update_meta_instance_dependencies {
788 if ( $self->{meta_instance_dependencies} ) {
789 return $self->add_meta_instance_dependencies;
793 sub add_meta_instance_dependencies {
796 $self->remove_meta_instance_dependencies;
798 my @attrs = $self->get_all_attributes();
801 my @classes = grep { not $seen{ $_->name }++ }
802 map { $_->associated_class } @attrs;
804 foreach my $class (@classes) {
805 $class->add_dependent_meta_instance($self);
808 $self->{meta_instance_dependencies} = \@classes;
811 sub remove_meta_instance_dependencies {
814 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
815 foreach my $class (@$classes) {
816 $class->remove_dependent_meta_instance($self);
826 sub add_dependent_meta_instance {
827 my ( $self, $metaclass ) = @_;
828 push @{ $self->{dependent_meta_instances} }, $metaclass;
831 sub remove_dependent_meta_instance {
832 my ( $self, $metaclass ) = @_;
833 my $name = $metaclass->name;
834 @$_ = grep { $_->name ne $name } @$_
835 for $self->{dependent_meta_instances};
838 sub invalidate_meta_instances {
840 $_->invalidate_meta_instance()
841 for $self, @{ $self->{dependent_meta_instances} };
844 sub invalidate_meta_instance {
846 undef $self->{_meta_instance};
849 # check if we can reinitialize
853 # if any local attr is defined
854 return if $self->get_attribute_list;
856 # or any non-declared methods
857 for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
858 return if $method->isa("Class::MOP::Method::Generated");
859 # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
868 sub is_immutable { 0 }
870 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
872 sub _immutable_options {
873 my ( $self, @args ) = @_;
876 inline_accessors => 1,
877 inline_constructor => 1,
878 inline_destructor => 0,
880 immutable_trait => $self->immutable_trait,
881 constructor_name => $self->constructor_name,
882 constructor_class => $self->constructor_class,
883 destructor_class => $self->destructor_class,
889 my ( $self, @args ) = @_;
891 if ( $self->is_mutable ) {
892 $self->_initialize_immutable( $self->_immutable_options(@args) );
893 $self->_rebless_as_immutable(@args);
904 if ( $self->is_immutable ) {
905 my @args = $self->immutable_options;
906 $self->_rebless_as_mutable();
907 $self->_remove_inlined_code(@args);
908 delete $self->{__immutable};
916 sub _rebless_as_immutable {
917 my ( $self, @args ) = @_;
919 $self->{__immutable}{original_class} = ref $self;
921 bless $self => $self->_immutable_metaclass(@args);
924 sub _immutable_metaclass {
925 my ( $self, %args ) = @_;
927 if ( my $class = $args{immutable_metaclass} ) {
931 my $trait = $args{immutable_trait} = $self->immutable_trait
932 || confess "no immutable trait specified for $self";
934 my $meta = $self->meta;
935 my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
939 if ( $meta_attr and $trait eq $meta_attr->default ) {
940 # if the trait is the same as the default we try and pick a
941 # predictable name for the immutable metaclass
942 $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
945 $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
946 $trait, 'ForMetaClass', ref($self);
950 if Class::MOP::is_class_loaded($class_name);
952 # If the metaclass is a subclass of CMOP::Class which has had
953 # metaclass roles applied (via Moose), then we want to make sure
954 # that we preserve that anonymous class (see Fey::ORM for an
955 # example of where this matters).
957 = $meta->is_immutable
958 ? $meta->_get_mutable_metaclass_name
961 my $immutable_meta = $meta_name->create(
963 superclasses => [ ref $self ],
966 Class::MOP::load_class($trait);
967 for my $meth ( Class::MOP::Class->initialize($trait)->get_all_methods ) {
968 my $meth_name = $meth->name;
970 if ( $immutable_meta->find_method_by_name( $meth_name ) ) {
971 $immutable_meta->add_around_method_modifier( $meth_name, $meth->body );
974 $immutable_meta->add_method( $meth_name, $meth->clone );
978 $immutable_meta->make_immutable(
979 inline_constructor => 0,
980 inline_accessors => 0,
986 sub _remove_inlined_code {
989 $self->remove_method( $_->name ) for $self->_inlined_methods;
991 delete $self->{__immutable}{inlined_methods};
994 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
996 sub _add_inlined_method {
997 my ( $self, $method ) = @_;
999 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1002 sub _initialize_immutable {
1003 my ( $self, %args ) = @_;
1005 $self->{__immutable}{options} = \%args;
1006 $self->_install_inlined_code(%args);
1009 sub _install_inlined_code {
1010 my ( $self, %args ) = @_;
1013 $self->_inline_accessors(%args) if $args{inline_accessors};
1014 $self->_inline_constructor(%args) if $args{inline_constructor};
1015 $self->_inline_destructor(%args) if $args{inline_destructor};
1018 sub _rebless_as_mutable {
1021 bless $self, $self->_get_mutable_metaclass_name;
1026 sub _inline_accessors {
1029 foreach my $attr_name ( $self->get_attribute_list ) {
1030 $self->get_attribute($attr_name)->install_accessors(1);
1034 sub _inline_constructor {
1035 my ( $self, %args ) = @_;
1037 my $name = $args{constructor_name};
1038 # A class may not even have a constructor, and that's okay.
1039 return unless defined $name;
1041 if ( $self->has_method($name) && !$args{replace_constructor} ) {
1042 my $class = $self->name;
1043 warn "Not inlining a constructor for $class since it defines"
1044 . " its own constructor.\n"
1045 . "If you are certain you don't need to inline your"
1046 . " constructor, specify inline_constructor => 0 in your"
1047 . " call to $class->meta->make_immutable\n";
1051 my $constructor_class = $args{constructor_class};
1053 Class::MOP::load_class($constructor_class);
1055 my $constructor = $constructor_class->new(
1059 package_name => $self->name,
1063 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1064 $self->add_method( $name => $constructor );
1065 $self->_add_inlined_method($constructor);
1069 sub _inline_destructor {
1070 my ( $self, %args ) = @_;
1072 ( exists $args{destructor_class} && defined $args{destructor_class} )
1073 || confess "The 'inline_destructor' option is present, but "
1074 . "no destructor class was specified";
1076 if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1077 my $class = $self->name;
1078 warn "Not inlining a destructor for $class since it defines"
1079 . " its own destructor.\n";
1083 my $destructor_class = $args{destructor_class};
1085 Class::MOP::load_class($destructor_class);
1087 return unless $destructor_class->is_needed($self);
1089 my $destructor = $destructor_class->new(
1092 package_name => $self->name,
1096 if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1097 $self->add_method( 'DESTROY' => $destructor );
1098 $self->_add_inlined_method($destructor);
1110 Class::MOP::Class - Class Meta Object
1114 # assuming that class Foo
1115 # has been defined, you can
1117 # use this for introspection ...
1119 # add a method to Foo ...
1120 Foo->meta->add_method( 'bar' => sub {...} )
1122 # get a list of all the classes searched
1123 # the method dispatcher in the correct order
1124 Foo->meta->class_precedence_list()
1126 # remove a method from Foo
1127 Foo->meta->remove_method('bar');
1129 # or use this to actually create classes ...
1131 Class::MOP::Class->create(
1134 superclasses => ['Foo'],
1136 Class::MOP::Attribute->new('$bar'),
1137 Class::MOP::Attribute->new('$baz'),
1140 calculate_bar => sub {...},
1141 construct_baz => sub {...}
1148 The Class Protocol is the largest and most complex part of the
1149 Class::MOP meta-object protocol. It controls the introspection and
1150 manipulation of Perl 5 classes, and it can create them as well. The
1151 best way to understand what this module can do is to read the
1152 documentation for each of its methods.
1156 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1160 =head2 Class construction
1162 These methods all create new C<Class::MOP::Class> objects. These
1163 objects can represent existing classes or they can be used to create
1164 new classes from scratch.
1166 The metaclass object for a given class is a singleton. If you attempt
1167 to create a metaclass for the same class twice, you will just get the
1172 =item B<< Class::MOP::Class->create($package_name, %options) >>
1174 This method creates a new C<Class::MOP::Class> object with the given
1175 package name. It accepts a number of options:
1181 An optional version number for the newly created package.
1185 An optional authority for the newly created package.
1187 =item * superclasses
1189 An optional array reference of superclass names.
1193 An optional hash reference of methods for the class. The keys of the
1194 hash reference are method names and values are subroutine references.
1198 An optional array reference of L<Class::MOP::Attribute> objects.
1202 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1204 This method works just like C<< Class::MOP::Class->create >> but it
1205 creates an "anonymous" class. In fact, the class does have a name, but
1206 that name is a unique name generated internally by this module.
1208 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1209 parameters that C<create> accepts.
1211 Anonymous classes are destroyed once the metaclass they are attached
1212 to goes out of scope, and will be removed from Perl's internal symbol
1215 All instances of an anonymous class keep a special reference to the
1216 metaclass object, which prevents the metaclass from going out of scope
1217 while any instances exist.
1219 This only works if the instance is based on a hash reference, however.
1221 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1223 This method will initialize a C<Class::MOP::Class> object for the
1224 named package. Unlike C<create>, this method I<will not> create a new
1227 The purpose of this method is to retrieve a C<Class::MOP::Class>
1228 object for introspecting an existing class.
1230 If an existing C<Class::MOP::Class> object exists for the named
1231 package, it will be returned, and any options provided will be
1234 If the object does not yet exist, it will be created.
1236 The valid options that can be passed to this method are
1237 C<attribute_metaclass>, C<method_metaclass>,
1238 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1239 optional, and default to the appropriate class in the C<Class::MOP>
1244 =head2 Object instance construction and cloning
1246 These methods are all related to creating and/or cloning object
1251 =item B<< $metaclass->clone_object($instance, %params) >>
1253 This method clones an existing object instance. Any parameters you
1254 provide are will override existing attribute values in the object.
1256 This is a convenience method for cloning an object instance, then
1257 blessing it into the appropriate package.
1259 You could implement a clone method in your class, using this method:
1262 my ($self, %params) = @_;
1263 $self->meta->clone_object($self, %params);
1266 =item B<< $metaclass->rebless_instance($instance, %params) >>
1268 This method changes the class of C<$instance> to the metaclass's class.
1270 You can only rebless an instance into a subclass of its current
1271 class. If you pass any additional parameters, these will be treated
1272 like constructor parameters and used to initialize the object's
1273 attributes. Any existing attributes that are already set will be
1276 Before reblessing the instance, this method will call
1277 C<rebless_instance_away> on the instance's current metaclass. This method
1278 will be passed the instance, the new metaclass, and any parameters
1279 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1280 does nothing; it is merely a hook.
1282 =item B<< $metaclass->rebless_instance_back($instance) >>
1284 Does the same thing as C<rebless_instance>, except that you can only
1285 rebless an instance into one of its superclasses. Any attributes that
1286 do not exist in the superclass will be deinitialized.
1288 This is a much more dangerous operation than C<rebless_instance>,
1289 especially when multiple inheritance is involved, so use this carefully!
1291 =item B<< $metaclass->new_object(%params) >>
1293 This method is used to create a new object of the metaclass's
1294 class. Any parameters you provide are used to initialize the
1295 instance's attributes. A special C<__INSTANCE__> key can be passed to
1296 provide an already generated instance, rather than having Class::MOP
1297 generate it for you. This is mostly useful for using Class::MOP with
1298 foreign classes which generate instances using their own constructors.
1300 =item B<< $metaclass->instance_metaclass >>
1302 Returns the class name of the instance metaclass. See
1303 L<Class::MOP::Instance> for more information on the instance
1306 =item B<< $metaclass->get_meta_instance >>
1308 Returns an instance of the C<instance_metaclass> to be used in the
1309 construction of a new instance of the class.
1313 =head2 Informational predicates
1315 These are a few predicate methods for asking information about the
1320 =item B<< $metaclass->is_anon_class >>
1322 This returns true if the class was created by calling C<<
1323 Class::MOP::Class->create_anon_class >>.
1325 =item B<< $metaclass->is_mutable >>
1327 This returns true if the class is still mutable.
1329 =item B<< $metaclass->is_immutable >>
1331 This returns true if the class has been made immutable.
1333 =item B<< $metaclass->is_pristine >>
1335 A class is I<not> pristine if it has non-inherited attributes or if it
1336 has any generated methods.
1340 =head2 Inheritance Relationships
1344 =item B<< $metaclass->superclasses(@superclasses) >>
1346 This is a read-write accessor which represents the superclass
1347 relationships of the metaclass's class.
1349 This is basically sugar around getting and setting C<@ISA>.
1351 =item B<< $metaclass->class_precedence_list >>
1353 This returns a list of all of the class's ancestor classes. The
1354 classes are returned in method dispatch order.
1356 =item B<< $metaclass->linearized_isa >>
1358 This returns a list based on C<class_precedence_list> but with all
1361 =item B<< $metaclass->subclasses >>
1363 This returns a list of all subclasses for this class, even indirect
1366 =item B<< $metaclass->direct_subclasses >>
1368 This returns a list of immediate subclasses for this class, which does not
1369 include indirect subclasses.
1373 =head2 Method introspection
1375 See L<Class::MOP::Package/Method introspection and creation> for
1376 methods that operate only on the current class. Class::MOP::Class adds
1377 introspection capabilities that take inheritance into account.
1381 =item B<< $metaclass->get_all_methods >>
1383 This will traverse the inheritance hierarchy and return a list of all
1384 the L<Class::MOP::Method> objects for this class and its parents.
1386 =item B<< $metaclass->find_method_by_name($method_name) >>
1388 This will return a L<Class::MOP::Method> for the specified
1389 C<$method_name>. If the class does not have the specified method, it
1392 Unlike C<get_method>, this method I<will> look for the named method in
1395 =item B<< $metaclass->get_all_method_names >>
1397 This will return a list of method I<names> for all of this class's
1398 methods, including inherited methods.
1400 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1402 This method looks for the named method in the class and all of its
1403 parents. It returns every matching method it finds in the inheritance
1404 tree, so it returns a list of methods.
1406 Each method is returned as a hash reference with three keys. The keys
1407 are C<name>, C<class>, and C<code>. The C<code> key has a
1408 L<Class::MOP::Method> object as its value.
1410 The list of methods is distinct.
1412 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1414 This method returns the first method in any superclass matching the
1415 given name. It is effectively the method that C<SUPER::$method_name>
1420 =head2 Attribute introspection and creation
1422 Because Perl 5 does not have a core concept of attributes in classes,
1423 we can only return information about attributes which have been added
1424 via this class's methods. We cannot discover information about
1425 attributes which are defined in terms of "regular" Perl 5 methods.
1429 =item B<< $metaclass->get_attribute($attribute_name) >>
1431 This will return a L<Class::MOP::Attribute> for the specified
1432 C<$attribute_name>. If the class does not have the specified
1433 attribute, it returns C<undef>.
1435 NOTE that get_attribute does not search superclasses, for that you
1436 need to use C<find_attribute_by_name>.
1438 =item B<< $metaclass->has_attribute($attribute_name) >>
1440 Returns a boolean indicating whether or not the class defines the
1441 named attribute. It does not include attributes inherited from parent
1444 =item B<< $metaclass->get_attribute_list >>
1446 This will return a list of attributes I<names> for all attributes
1447 defined in this class.
1449 =item B<< $metaclass->get_all_attributes >>
1451 This will traverse the inheritance hierarchy and return a list of all
1452 the L<Class::MOP::Attribute> objects for this class and its parents.
1454 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1456 This will return a L<Class::MOP::Attribute> for the specified
1457 C<$attribute_name>. If the class does not have the specified
1458 attribute, it returns C<undef>.
1460 Unlike C<get_attribute>, this attribute I<will> look for the named
1461 attribute in superclasses.
1463 =item B<< $metaclass->add_attribute(...) >>
1465 This method accepts either an existing L<Class::MOP::Attribute>
1466 object or parameters suitable for passing to that class's C<new>
1469 The attribute provided will be added to the class.
1471 Any accessor methods defined by the attribute will be added to the
1472 class when the attribute is added.
1474 If an attribute of the same name already exists, the old attribute
1475 will be removed first.
1477 =item B<< $metaclass->remove_attribute($attribute_name) >>
1479 This will remove the named attribute from the class, and
1480 L<Class::MOP::Attribute> object.
1482 Removing an attribute also removes any accessor methods defined by the
1485 However, note that removing an attribute will only affect I<future>
1486 object instances created for this class, not existing instances.
1488 =item B<< $metaclass->attribute_metaclass >>
1490 Returns the class name of the attribute metaclass for this class. By
1491 default, this is L<Class::MOP::Attribute>.
1495 =head2 Class Immutability
1497 Making a class immutable "freezes" the class definition. You can no
1498 longer call methods which alter the class, such as adding or removing
1499 methods or attributes.
1501 Making a class immutable lets us optimize the class by inlining some
1502 methods, and also allows us to optimize some methods on the metaclass
1505 After immutabilization, the metaclass object will cache most informational
1506 methods that returns information about methods or attributes. Methods which
1507 would alter the class, such as C<add_attribute> and C<add_method>, will
1508 throw an error on an immutable metaclass object.
1510 The immutabilization system in L<Moose> takes much greater advantage
1511 of the inlining features than Class::MOP itself does.
1515 =item B<< $metaclass->make_immutable(%options) >>
1517 This method will create an immutable transformer and use it to make
1518 the class and its metaclass object immutable.
1520 This method accepts the following options:
1524 =item * inline_accessors
1526 =item * inline_constructor
1528 =item * inline_destructor
1530 These are all booleans indicating whether the specified method(s)
1533 By default, accessors and the constructor are inlined, but not the
1536 =item * immutable_trait
1538 The name of a class which will be used as a parent class for the
1539 metaclass object being made immutable. This "trait" implements the
1540 post-immutability functionality of the metaclass (but not the
1541 transformation itself).
1543 This defaults to L<Class::MOP::Class::Immutable::Trait>.
1545 =item * constructor_name
1547 This is the constructor method name. This defaults to "new".
1549 =item * constructor_class
1551 The name of the method metaclass for constructors. It will be used to
1552 generate the inlined constructor. This defaults to
1553 "Class::MOP::Method::Constructor".
1555 =item * replace_constructor
1557 This is a boolean indicating whether an existing constructor should be
1558 replaced when inlining a constructor. This defaults to false.
1560 =item * destructor_class
1562 The name of the method metaclass for destructors. It will be used to
1563 generate the inlined destructor. This defaults to
1564 "Class::MOP::Method::Denstructor".
1566 =item * replace_destructor
1568 This is a boolean indicating whether an existing destructor should be
1569 replaced when inlining a destructor. This defaults to false.
1573 =item B<< $metaclass->immutable_options >>
1575 Returns a hash of the options used when making the class immutable, including
1576 both defaults and anything supplied by the user in the call to C<<
1577 $metaclass->make_immutable >>. This is useful if you need to temporarily make
1578 a class mutable and then restore immutability as it was before.
1580 =item B<< $metaclass->make_mutable >>
1582 Calling this method reverse the immutabilization transformation.
1586 =head2 Method Modifiers
1588 Method modifiers are hooks which allow a method to be wrapped with
1589 I<before>, I<after> and I<around> method modifiers. Every time a
1590 method is called, its modifiers are also called.
1592 A class can modify its own methods, as well as methods defined in
1595 =head3 How method modifiers work?
1597 Method modifiers work by wrapping the original method and then
1598 replacing it in the class's symbol table. The wrappers will handle
1599 calling all the modifiers in the appropriate order and preserving the
1600 calling context for the original method.
1602 The return values of C<before> and C<after> modifiers are
1603 ignored. This is because their purpose is B<not> to filter the input
1604 and output of the primary method (this is done with an I<around>
1607 This may seem like an odd restriction to some, but doing this allows
1608 for simple code to be added at the beginning or end of a method call
1609 without altering the function of the wrapped method or placing any
1610 extra responsibility on the code of the modifier.
1612 Of course if you have more complex needs, you can use the C<around>
1613 modifier which allows you to change both the parameters passed to the
1614 wrapped method, as well as its return value.
1616 Before and around modifiers are called in last-defined-first-called
1617 order, while after modifiers are called in first-defined-first-called
1618 order. So the call tree might looks something like this:
1630 =head3 What is the performance impact?
1632 Of course there is a performance cost associated with method
1633 modifiers, but we have made every effort to make that cost directly
1634 proportional to the number of modifier features you use.
1636 The wrapping method does its best to B<only> do as much work as it
1637 absolutely needs to. In order to do this we have moved some of the
1638 performance costs to set-up time, where they are easier to amortize.
1640 All this said, our benchmarks have indicated the following:
1642 simple wrapper with no modifiers 100% slower
1643 simple wrapper with simple before modifier 400% slower
1644 simple wrapper with simple after modifier 450% slower
1645 simple wrapper with simple around modifier 500-550% slower
1646 simple wrapper with all 3 modifiers 1100% slower
1648 These numbers may seem daunting, but you must remember, every feature
1649 comes with some cost. To put things in perspective, just doing a
1650 simple C<AUTOLOAD> which does nothing but extract the name of the
1651 method called and return it costs about 400% over a normal method
1656 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
1658 This wraps the specified method with the supplied subroutine
1659 reference. The modifier will be called as a method itself, and will
1660 receive the same arguments as are passed to the method.
1662 When the modifier exits, the wrapped method will be called.
1664 The return value of the modifier will be ignored.
1666 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
1668 This wraps the specified method with the supplied subroutine
1669 reference. The modifier will be called as a method itself, and will
1670 receive the same arguments as are passed to the method.
1672 When the wrapped methods exits, the modifier will be called.
1674 The return value of the modifier will be ignored.
1676 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
1678 This wraps the specified method with the supplied subroutine
1681 The first argument passed to the modifier will be a subroutine
1682 reference to the wrapped method. The second argument is the object,
1683 and after that come any arguments passed when the method is called.
1685 The around modifier can choose to call the original method, as well as
1686 what arguments to pass if it does so.
1688 The return value of the modifier is what will be seen by the caller.
1692 =head2 Introspection
1696 =item B<< Class::MOP::Class->meta >>
1698 This will return a L<Class::MOP::Class> instance for this class.
1700 It should also be noted that L<Class::MOP> will actually bootstrap
1701 this module by installing a number of attribute meta-objects into its
1708 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1710 =head1 COPYRIGHT AND LICENSE
1712 Copyright 2006-2010 by Infinity Interactive, Inc.
1714 L<http://www.iinteractive.com>
1716 This library is free software; you can redistribute it and/or modify
1717 it under the same terms as Perl itself.