2 package Class::MOP::Class;
7 use Class::MOP::Instance;
8 use Class::MOP::Method::Wrapped;
9 use Class::MOP::Method::Accessor;
10 use Class::MOP::Method::Constructor;
11 use Class::MOP::Class::Immutable::Class::MOP::Class;
14 use Scalar::Util 'blessed', 'weaken';
16 our $VERSION = '0.81';
17 $VERSION = eval $VERSION;
18 our $AUTHORITY = 'cpan:STEVAN';
20 use base 'Class::MOP::Module';
30 $package_name = shift;
33 $package_name = $options{package};
36 (defined $package_name && $package_name && !ref($package_name))
37 || confess "You must pass a package name and it cannot be blessed";
39 return Class::MOP::get_metaclass_by_name($package_name)
40 || $class->_construct_class_instance(package => $package_name, @_);
43 sub construct_class_instance {
44 Carp::cluck('The construct_class_instance method has been made private.'
45 . " The public version is deprecated and will be removed in a future release.\n");
46 shift->_construct_class_instance(@_);
49 # NOTE: (meta-circularity)
50 # this is a special form of _construct_instance
51 # (see below), which is used to construct class
52 # meta-object instances for any Class::MOP::*
53 # class. All other classes will use the more
54 # normal &construct_instance.
55 sub _construct_class_instance {
57 my $options = @_ == 1 ? $_[0] : {@_};
58 my $package_name = $options->{package};
59 (defined $package_name && $package_name)
60 || confess "You must pass a package name";
62 # return the metaclass if we have it cached,
63 # and it is still defined (it has not been
64 # reaped by DESTROY yet, which can happen
65 # annoyingly enough during global destruction)
67 if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
72 # we need to deal with the possibility
73 # of class immutability here, and then
74 # get the name of the class appropriately
76 ? ($class->is_immutable
77 ? $class->get_mutable_metaclass_name()
81 # now create the metaclass
83 if ($class eq 'Class::MOP::Class') {
84 $meta = $class->_new($options);
88 # it is safe to use meta here because
89 # class will always be a subclass of
90 # Class::MOP::Class, which defines meta
91 $meta = $class->meta->_construct_instance($options)
94 # and check the metaclass compatibility
95 $meta->_check_metaclass_compatibility();
97 Class::MOP::store_metaclass_by_name($package_name, $meta);
100 # we need to weaken any anon classes
101 # so that they can call DESTROY properly
102 Class::MOP::weaken_metaclass($package_name) if $meta->is_anon_class;
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,
125 # inherited from Class::MOP::Module
127 'authority' => \undef,
129 # defined in Class::MOP::Class
130 'superclasses' => \undef,
134 'attribute_metaclass' => ( $options->{'attribute_metaclass'} || 'Class::MOP::Attribute' ),
135 'method_metaclass' => ( $options->{'method_metaclass'} || 'Class::MOP::Method' ),
136 'wrapped_method_metaclass' => ( $options->{'wrapped_method_metaclass'} || 'Class::MOP::Method::Wrapped' ),
137 'instance_metaclass' => ( $options->{'instance_metaclass'} || 'Class::MOP::Instance' ),
138 'immutable_trait' => ( $options->{'immutable_trait'} || 'Class::MOP::Class::Immutable::Trait' ),
139 'constructor_name' => ( $options->{constructor_name} || 'new' ),
140 'constructor_class' => ( $options->{constructor_class} || 'Class::MOP::Method::Constructor' ),
141 'destructor_class' => $options->{destructor_class},
145 sub reset_package_cache_flag { (shift)->{'_package_cache_flag'} = undef }
146 sub update_package_cache_flag {
149 # we can manually update the cache number
150 # since we are actually adding the method
151 # to our cache as well. This avoids us
152 # having to regenerate the method_map.
154 $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
158 sub check_metaclass_compatibility {
159 Carp::cluck('The check_metaclass_compatibility method has been made private.'
160 . " The public version is deprecated and will be removed in a future release.\n");
161 shift->_check_metaclass_compatibility(@_);
164 sub _check_metaclass_compatibility {
167 # this is always okay ...
168 return if ref($self) eq 'Class::MOP::Class' &&
169 $self->instance_metaclass eq 'Class::MOP::Instance';
171 my @class_list = $self->linearized_isa;
172 shift @class_list; # shift off $self->name
174 foreach my $superclass_name (@class_list) {
175 my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name) || next;
178 # we need to deal with the possibility
179 # of class immutability here, and then
180 # get the name of the class appropriately
182 = $super_meta->is_immutable
183 ? $super_meta->get_mutable_metaclass_name()
186 ($self->isa($super_meta_type))
187 || confess "Class::MOP::class_of(" . $self->name . ") => ("
188 . (ref($self)) . ")" . " is not compatible with the " .
189 "Class::MOP::class_of(".$superclass_name . ") => ("
190 . ($super_meta_type) . ")";
192 # we also need to check that instance metaclasses
193 # are compatibile in the same the class.
194 ($self->instance_metaclass->isa($super_meta->instance_metaclass))
195 || confess "Class::MOP::class_of(" . $self->name . ")->instance_metaclass => (" . ($self->instance_metaclass) . ")" .
196 " is not compatible with the " .
197 "Class::MOP::class_of(" . $superclass_name . ")->instance_metaclass => (" . ($super_meta->instance_metaclass) . ")";
205 # this should be sufficient, if you have a
206 # use case where it is not, write a test and
208 my $ANON_CLASS_SERIAL = 0;
211 # we need a sufficiently annoying prefix
212 # this should suffice for now, this is
213 # used in a couple of places below, so
214 # need to put it up here for now.
215 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
219 no warnings 'uninitialized';
220 $self->name =~ /^$ANON_CLASS_PREFIX/;
223 sub create_anon_class {
224 my ($class, %options) = @_;
225 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
226 return $class->create($package_name, %options);
230 # this will only get called for
231 # anon-classes, all other calls
232 # are assumed to occur during
233 # global destruction and so don't
234 # really need to be handled explicitly
238 return if Class::MOP::in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
240 no warnings 'uninitialized';
241 return unless $self->name =~ /^$ANON_CLASS_PREFIX/;
242 # Moose does a weird thing where it replaces the metaclass for
243 # class when fixing metaclass incompatibility. In that case,
244 # we don't want to clean out the namespace now. We can detect
245 # that because Moose will explicitly update the singleton
246 # cache in Class::MOP.
247 my $current_meta = Class::MOP::get_metaclass_by_name($self->name);
248 return if $current_meta ne $self;
250 my ($serial_id) = ($self->name =~ /^$ANON_CLASS_PREFIX(\d+)/);
252 foreach my $key (keys %{$ANON_CLASS_PREFIX . $serial_id}) {
253 delete ${$ANON_CLASS_PREFIX . $serial_id}{$key};
255 delete ${'main::' . $ANON_CLASS_PREFIX}{$serial_id . '::'};
260 # creating classes with MOP ...
263 my ( $class, @args ) = @_;
265 unshift @args, 'package' if @args % 2 == 1;
267 my (%options) = @args;
268 my $package_name = $options{package};
270 (ref $options{superclasses} eq 'ARRAY')
271 || confess "You must pass an ARRAY ref of superclasses"
272 if exists $options{superclasses};
274 (ref $options{attributes} eq 'ARRAY')
275 || confess "You must pass an ARRAY ref of attributes"
276 if exists $options{attributes};
278 (ref $options{methods} eq 'HASH')
279 || confess "You must pass a HASH ref of methods"
280 if exists $options{methods};
282 my (%initialize_options) = @args;
283 delete @initialize_options{qw(
291 my $meta = $class->initialize( $package_name => %initialize_options );
293 $meta->_instantiate_module( $options{version}, $options{authority} );
296 $meta->add_method('meta' => sub {
297 $class->initialize(ref($_[0]) || $_[0]);
300 $meta->superclasses(@{$options{superclasses}})
301 if exists $options{superclasses};
303 # process attributes first, so that they can
304 # install accessors, but locally defined methods
305 # can then overwrite them. It is maybe a little odd, but
306 # I think this should be the order of things.
307 if (exists $options{attributes}) {
308 foreach my $attr (@{$options{attributes}}) {
309 $meta->add_attribute($attr);
312 if (exists $options{methods}) {
313 foreach my $method_name (keys %{$options{methods}}) {
314 $meta->add_method($method_name, $options{methods}->{$method_name});
323 # all these attribute readers will be bootstrapped
324 # away in the Class::MOP bootstrap section
326 sub get_attribute_map { $_[0]->{'attributes'} }
327 sub attribute_metaclass { $_[0]->{'attribute_metaclass'} }
328 sub method_metaclass { $_[0]->{'method_metaclass'} }
329 sub wrapped_method_metaclass { $_[0]->{'wrapped_method_metaclass'} }
330 sub instance_metaclass { $_[0]->{'instance_metaclass'} }
331 sub immutable_trait { $_[0]->{'immutable_trait'} }
332 sub constructor_class { $_[0]->{'constructor_class'} }
333 sub constructor_name { $_[0]->{'constructor_name'} }
334 sub destructor_class { $_[0]->{'destructor_class'} }
336 # Instance Construction & Cloning
342 # we need to protect the integrity of the
343 # Class::MOP::Class singletons here, so we
344 # delegate this to &construct_class_instance
345 # which will deal with the singletons
346 return $class->_construct_class_instance(@_)
347 if $class->name->isa('Class::MOP::Class');
348 return $class->_construct_instance(@_);
351 sub construct_instance {
352 Carp::cluck('The construct_instance method has been made private.'
353 . " The public version is deprecated and will be removed in a future release.\n");
354 shift->_construct_instance(@_);
357 sub _construct_instance {
359 my $params = @_ == 1 ? $_[0] : {@_};
360 my $meta_instance = $class->get_meta_instance();
361 my $instance = $meta_instance->create_instance();
362 foreach my $attr ($class->get_all_attributes()) {
363 $attr->initialize_instance_slot($meta_instance, $instance, $params);
366 # this will only work for a HASH instance type
367 if ($class->is_anon_class) {
368 (Scalar::Util::reftype($instance) eq 'HASH')
369 || confess "Currently only HASH based instances are supported with instance of anon-classes";
371 # At some point we should make this official
372 # as a reserved slot name, but right now I am
373 # going to keep it here.
374 # my $RESERVED_MOP_SLOT = '__MOP__';
375 $instance->{'__MOP__'} = $class;
381 sub get_meta_instance {
383 $self->{'_meta_instance'} ||= $self->_create_meta_instance();
386 sub create_meta_instance {
387 Carp::cluck('The create_meta_instance method has been made private.'
388 . " The public version is deprecated and will be removed in a future release.\n");
389 shift->_create_meta_instance(@_);
392 sub _create_meta_instance {
395 my $instance = $self->instance_metaclass->new(
396 associated_metaclass => $self,
397 attributes => [ $self->get_all_attributes() ],
400 $self->add_meta_instance_dependencies()
401 if $instance->is_dependent_on_superclasses();
408 my $instance = shift;
409 (blessed($instance) && $instance->isa($class->name))
410 || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
413 # we need to protect the integrity of the
414 # Class::MOP::Class singletons here, they
415 # should not be cloned.
416 return $instance if $instance->isa('Class::MOP::Class');
417 $class->_clone_instance($instance, @_);
421 Carp::cluck('The clone_instance method has been made private.'
422 . " The public version is deprecated and will be removed in a future release.\n");
423 shift->_clone_instance(@_);
426 sub _clone_instance {
427 my ($class, $instance, %params) = @_;
429 || confess "You can only clone instances, ($instance) is not a blessed instance";
430 my $meta_instance = $class->get_meta_instance();
431 my $clone = $meta_instance->clone_instance($instance);
432 foreach my $attr ($class->get_all_attributes()) {
433 if ( defined( my $init_arg = $attr->init_arg ) ) {
434 if (exists $params{$init_arg}) {
435 $attr->set_value($clone, $params{$init_arg});
442 sub rebless_instance {
443 my ($self, $instance, %params) = @_;
445 my $old_metaclass = Class::MOP::class_of($instance);
447 my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
448 $self->name->isa($old_class)
449 || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
451 $old_metaclass->rebless_instance_away($instance, $self, %params)
454 my $meta_instance = $self->get_meta_instance();
457 # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
458 $meta_instance->rebless_instance_structure($_[1], $self);
460 foreach my $attr ( $self->get_all_attributes ) {
461 if ( $attr->has_value($instance) ) {
462 if ( defined( my $init_arg = $attr->init_arg ) ) {
463 $params{$init_arg} = $attr->get_value($instance)
464 unless exists $params{$init_arg};
467 $attr->set_value($instance, $attr->get_value($instance));
472 foreach my $attr ($self->get_all_attributes) {
473 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
479 sub rebless_instance_away {
480 # this intentionally does nothing, it is just a hook
487 my $var_spec = { sigil => '@', type => 'ARRAY', name => 'ISA' };
490 @{$self->get_package_symbol($var_spec)} = @supers;
493 # on 5.8 and below, we need to call
494 # a method to get Perl to detect
495 # a cycle in the class hierarchy
496 my $class = $self->name;
500 # we need to check the metaclass
501 # compatibility here so that we can
502 # be sure that the superclass is
503 # not potentially creating an issues
504 # we don't know about
506 $self->_check_metaclass_compatibility();
507 $self->update_meta_instance_dependencies();
509 @{$self->get_package_symbol($var_spec)};
514 my $super_class = $self->name;
516 return @{ $super_class->mro::get_isarev() };
521 return @{ mro::get_linear_isa( (shift)->name ) };
524 sub class_precedence_list {
526 my $name = $self->name;
528 unless (Class::MOP::IS_RUNNING_ON_5_10()) {
530 # We need to check for circular inheritance here
531 # if we are are not on 5.10, cause 5.8 detects it
532 # late. This will do nothing if all is well, and
533 # blow up otherwise. Yes, it's an ugly hack, better
534 # suggestions are welcome.
536 ($name || return)->isa('This is a test for circular inheritance')
539 # if our mro is c3, we can
540 # just grab the linear_isa
541 if (mro::get_mro($name) eq 'c3') {
542 return @{ mro::get_linear_isa($name) }
546 # we can't grab the linear_isa for dfs
547 # since it has all the duplicates
552 $self->initialize($_)->class_precedence_list()
553 } $self->superclasses()
560 sub wrap_method_body {
561 my ( $self, %args ) = @_;
563 ('CODE' eq ref $args{body})
564 || confess "Your code block must be a CODE reference";
566 $self->method_metaclass->wrap(
567 package_name => $self->name,
573 my ($self, $method_name, $method) = @_;
574 (defined $method_name && $method_name)
575 || confess "You must define a method name";
578 if (blessed($method)) {
579 $body = $method->body;
580 if ($method->package_name ne $self->name) {
581 $method = $method->clone(
582 package_name => $self->name,
584 ) if $method->can('clone');
589 $method = $self->wrap_method_body( body => $body, name => $method_name );
592 $method->attach_to_class($self);
594 # This used to call get_method_map, which meant we would build all
595 # the method objects for the class just because we added one
596 # method. This is hackier, but quicker too.
597 $self->{methods}{$method_name} = $method;
599 my $full_method_name = ($self->name . '::' . $method_name);
600 $self->add_package_symbol(
601 { sigil => '&', type => 'CODE', name => $method_name },
602 Class::MOP::subname($full_method_name => $body)
607 my $fetch_and_prepare_method = sub {
608 my ($self, $method_name) = @_;
609 my $wrapped_metaclass = $self->wrapped_method_metaclass;
611 my $method = $self->get_method($method_name);
612 # if we dont have local ...
614 # try to find the next method
615 $method = $self->find_next_method_by_name($method_name);
616 # die if it does not exist
618 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
619 # and now make sure to wrap it
620 # even if it is already wrapped
621 # because we need a new sub ref
622 $method = $wrapped_metaclass->wrap($method);
625 # now make sure we wrap it properly
626 $method = $wrapped_metaclass->wrap($method)
627 unless $method->isa($wrapped_metaclass);
629 $self->add_method($method_name => $method);
633 sub add_before_method_modifier {
634 my ($self, $method_name, $method_modifier) = @_;
635 (defined $method_name && $method_name)
636 || confess "You must pass in a method name";
637 my $method = $fetch_and_prepare_method->($self, $method_name);
638 $method->add_before_modifier(
639 Class::MOP::subname(':before' => $method_modifier)
643 sub add_after_method_modifier {
644 my ($self, $method_name, $method_modifier) = @_;
645 (defined $method_name && $method_name)
646 || confess "You must pass in a method name";
647 my $method = $fetch_and_prepare_method->($self, $method_name);
648 $method->add_after_modifier(
649 Class::MOP::subname(':after' => $method_modifier)
653 sub add_around_method_modifier {
654 my ($self, $method_name, $method_modifier) = @_;
655 (defined $method_name && $method_name)
656 || confess "You must pass in a method name";
657 my $method = $fetch_and_prepare_method->($self, $method_name);
658 $method->add_around_modifier(
659 Class::MOP::subname(':around' => $method_modifier)
664 # the methods above used to be named like this:
665 # ${pkg}::${method}:(before|after|around)
666 # but this proved problematic when using one modifier
667 # to wrap multiple methods (something which is likely
668 # to happen pretty regularly IMO). So instead of naming
669 # it like this, I have chosen to just name them purely
670 # with their modifier names, like so:
671 # :(before|after|around)
672 # The fact is that in a stack trace, it will be fairly
673 # evident from the context what method they are attached
674 # to, and so don't need the fully qualified name.
678 Carp::cluck("The alias_method method is deprecated. Use add_method instead.\n");
680 shift->add_method(@_);
684 my ($self, $method_name) = @_;
685 (defined $method_name && $method_name)
686 || confess "You must define a method name";
688 exists $self->{methods}{$method_name} || exists $self->get_method_map->{$method_name};
692 my ($self, $method_name) = @_;
693 (defined $method_name && $method_name)
694 || confess "You must define a method name";
696 return $self->{methods}{$method_name} || $self->get_method_map->{$method_name};
700 my ($self, $method_name) = @_;
701 (defined $method_name && $method_name)
702 || confess "You must define a method name";
704 my $removed_method = delete $self->get_method_map->{$method_name};
706 $self->remove_package_symbol(
707 { sigil => '&', type => 'CODE', name => $method_name }
710 $removed_method->detach_from_class if $removed_method;
712 $self->update_package_cache_flag; # still valid, since we just removed the method from the map
714 return $removed_method;
717 sub get_method_list {
719 keys %{$self->get_method_map};
722 sub find_method_by_name {
723 my ($self, $method_name) = @_;
724 (defined $method_name && $method_name)
725 || confess "You must define a method name to find";
726 foreach my $class ($self->linearized_isa) {
727 # fetch the meta-class ...
728 my $meta = $self->initialize($class);
729 return $meta->get_method($method_name)
730 if $meta->has_method($method_name);
735 sub get_all_methods {
737 my %methods = map { %{ $self->initialize($_)->get_method_map } } reverse $self->linearized_isa;
738 return values %methods;
741 sub compute_all_applicable_methods {
742 Carp::cluck('The compute_all_applicable_methods method is deprecated.'
743 . " Use get_all_methods instead.\n");
748 class => $_->package_name,
749 code => $_, # sigh, overloading
751 } shift->get_all_methods(@_);
754 sub get_all_method_names {
757 grep { $uniq{$_}++ == 0 } map { $_->name } $self->get_all_methods;
760 sub find_all_methods_by_name {
761 my ($self, $method_name) = @_;
762 (defined $method_name && $method_name)
763 || confess "You must define a method name to find";
765 foreach my $class ($self->linearized_isa) {
766 # fetch the meta-class ...
767 my $meta = $self->initialize($class);
769 name => $method_name,
771 code => $meta->get_method($method_name)
772 } if $meta->has_method($method_name);
777 sub find_next_method_by_name {
778 my ($self, $method_name) = @_;
779 (defined $method_name && $method_name)
780 || confess "You must define a method name to find";
781 my @cpl = $self->linearized_isa;
782 shift @cpl; # discard ourselves
783 foreach my $class (@cpl) {
784 # fetch the meta-class ...
785 my $meta = $self->initialize($class);
786 return $meta->get_method($method_name)
787 if $meta->has_method($method_name);
796 # either we have an attribute object already
797 # or we need to create one from the args provided
798 my $attribute = blessed($_[0]) ? $_[0] : $self->attribute_metaclass->new(@_);
799 # make sure it is derived from the correct type though
800 ($attribute->isa('Class::MOP::Attribute'))
801 || confess "Your attribute must be an instance of Class::MOP::Attribute (or a subclass)";
803 # first we attach our new attribute
804 # because it might need certain information
805 # about the class which it is attached to
806 $attribute->attach_to_class($self);
808 # then we remove attributes of a conflicting
809 # name here so that we can properly detach
810 # the old attr object, and remove any
811 # accessors it would have generated
812 if ( $self->has_attribute($attribute->name) ) {
813 $self->remove_attribute($attribute->name);
815 $self->invalidate_meta_instances();
818 # then onto installing the new accessors
819 $self->get_attribute_map->{$attribute->name} = $attribute;
821 # invalidate package flag here
822 my $e = do { local $@; eval { $attribute->install_accessors() }; $@ };
824 $self->remove_attribute($attribute->name);
831 sub update_meta_instance_dependencies {
834 if ( $self->{meta_instance_dependencies} ) {
835 return $self->add_meta_instance_dependencies;
839 sub add_meta_instance_dependencies {
842 $self->remove_meta_instance_dependencies;
844 my @attrs = $self->get_all_attributes();
847 my @classes = grep { not $seen{$_->name}++ } map { $_->associated_class } @attrs;
849 foreach my $class ( @classes ) {
850 $class->add_dependent_meta_instance($self);
853 $self->{meta_instance_dependencies} = \@classes;
856 sub remove_meta_instance_dependencies {
859 if ( my $classes = delete $self->{meta_instance_dependencies} ) {
860 foreach my $class ( @$classes ) {
861 $class->remove_dependent_meta_instance($self);
871 sub add_dependent_meta_instance {
872 my ( $self, $metaclass ) = @_;
873 push @{ $self->{dependent_meta_instances} }, $metaclass;
876 sub remove_dependent_meta_instance {
877 my ( $self, $metaclass ) = @_;
878 my $name = $metaclass->name;
879 @$_ = grep { $_->name ne $name } @$_ for $self->{dependent_meta_instances};
882 sub invalidate_meta_instances {
884 $_->invalidate_meta_instance() for $self, @{ $self->{dependent_meta_instances} };
887 sub invalidate_meta_instance {
889 undef $self->{_meta_instance};
893 my ($self, $attribute_name) = @_;
894 (defined $attribute_name && $attribute_name)
895 || confess "You must define an attribute name";
896 exists $self->get_attribute_map->{$attribute_name};
900 my ($self, $attribute_name) = @_;
901 (defined $attribute_name && $attribute_name)
902 || confess "You must define an attribute name";
903 return $self->get_attribute_map->{$attribute_name}
905 # this will return undef anyway, so no need ...
906 # if $self->has_attribute($attribute_name);
910 sub remove_attribute {
911 my ($self, $attribute_name) = @_;
912 (defined $attribute_name && $attribute_name)
913 || confess "You must define an attribute name";
914 my $removed_attribute = $self->get_attribute_map->{$attribute_name};
915 return unless defined $removed_attribute;
916 delete $self->get_attribute_map->{$attribute_name};
917 $self->invalidate_meta_instances();
918 $removed_attribute->remove_accessors();
919 $removed_attribute->detach_from_class();
920 return $removed_attribute;
923 sub get_attribute_list {
925 keys %{$self->get_attribute_map};
928 sub get_all_attributes {
930 my %attrs = map { %{ $self->initialize($_)->get_attribute_map } } reverse $self->linearized_isa;
931 return values %attrs;
934 sub compute_all_applicable_attributes {
935 Carp::cluck('The compute_all_applicable_attributes method has been deprecated.'
936 . " Use get_all_attributes instead.\n");
938 shift->get_all_attributes(@_);
941 sub find_attribute_by_name {
942 my ($self, $attr_name) = @_;
943 foreach my $class ($self->linearized_isa) {
944 # fetch the meta-class ...
945 my $meta = $self->initialize($class);
946 return $meta->get_attribute($attr_name)
947 if $meta->has_attribute($attr_name);
952 # check if we can reinitialize
956 # if any local attr is defined
957 return if $self->get_attribute_list;
959 # or any non-declared methods
960 if ( my @methods = values %{ $self->get_method_map } ) {
961 my $metaclass = $self->method_metaclass;
962 foreach my $method ( @methods ) {
963 return if $method->isa("Class::MOP::Method::Generated");
964 # FIXME do we need to enforce this too? return unless $method->isa($metaclass);
974 sub is_immutable { 0 }
975 sub immutable_transformer { return }
977 sub _immutable_options {
978 my ( $self, @args ) = @_;
981 inline_accessors => 1,
982 inline_constructor => 1,
983 inline_destructor => 0,
985 immutable_trait => $self->immutable_trait,
986 constructor_name => $self->constructor_name,
987 constructor_class => $self->constructor_class,
988 destructor_class => $self->destructor_class,
994 my ( $self, @args ) = @_;
996 if ( $self->is_mutable ) {
997 $self->_initialize_immutable($self->_immutable_options(@args));
998 $self->_rebless_as_immutable(@args);
1009 if ( $self->is_immutable ) {
1010 my @args = $self->immutable_options;
1011 $self->_rebless_as_mutable();
1012 $self->_remove_inlined_code(@args);
1013 delete $self->{__immutable};
1020 sub immutable_metaclass {
1021 my ( $self, %args ) = @_;
1023 if ( my $class = $args{immutable_metaclass} ) {
1027 my $trait = $args{immutable_trait} = $self->immutable_trait
1028 || confess "no immutable trait specified for $self";
1030 my $meta_attr = $self->meta->find_attribute_by_name("immutable_trait");
1034 if ( $meta_attr and $trait eq $meta_attr->default ) {
1035 # if the trait is the same as the default we try and pick a predictable
1036 # name for the immutable metaclass
1037 $class_name = "Class::MOP::Class::Immutable::" . ref($self);
1039 $class_name = join("::", "Class::MOP::Class::Immutable::CustomTrait", $trait, "ForMetaClass", ref($self));
1042 if ( Class::MOP::is_class_loaded($class_name) ) {
1043 if ( $class_name->isa($trait) ) {
1046 confess "$class_name is already defined but does not inherit $trait";
1049 my @super = ( $trait, ref($self) );
1051 my $meta = Class::MOP::Class->initialize($class_name);
1052 $meta->superclasses(@super);
1054 $meta->make_immutable;
1060 sub _rebless_as_immutable {
1061 my ( $self, @args ) = @_;
1063 $self->{__immutable}{original_class} = ref $self;
1065 bless $self => $self->immutable_metaclass(@args);
1068 sub _remove_inlined_code {
1071 $self->remove_method($_->name) for $self->_inlined_methods;
1073 delete $self->{__immutable}{inlined_methods};
1076 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } };
1078 sub _add_inlined_method {
1079 my ( $self, $method ) = @_;
1081 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1084 sub _initialize_immutable {
1085 my ( $self, %args ) = @_;
1087 $self->{__immutable}{options} = \%args;
1088 $self->_install_inlined_code(%args);
1091 sub _install_inlined_code {
1092 my ( $self, %args ) = @_;
1095 $self->_inline_accessors(%args) if $args{inline_accessors};
1096 $self->_inline_constructor(%args) if $args{inline_constructor};
1097 $self->_inline_destructor(%args) if $args{inline_destructor};
1100 sub _rebless_as_mutable {
1103 bless $self, $self->get_mutable_metaclass_name;
1108 sub _inline_accessors {
1111 foreach my $attr_name ( $self->get_attribute_list ) {
1112 $self->get_attribute($attr_name)->install_accessors(1);
1116 sub _inline_constructor {
1117 my ( $self, %args ) = @_;
1119 my $name = $args{constructor_name};
1121 #if ( my $existing = $self->name->can($args{constructor_name}) ) {
1122 # if ( refaddr($existing) == refaddr(\&Moose::Object::new) ) {
1124 unless ($args{replace_constructor}
1125 or !$self->has_method($name) ) {
1126 my $class = $self->name;
1127 warn "Not inlining a constructor for $class since it defines"
1128 . " its own constructor.\n"
1129 . "If you are certain you don't need to inline your"
1130 . " constructor, specify inline_constructor => 0 in your"
1131 . " call to $class->meta->make_immutable\n";
1135 my $constructor_class = $args{constructor_class};
1137 Class::MOP::load_class($constructor_class);
1139 my $constructor = $constructor_class->new(
1143 package_name => $self->name,
1147 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1148 $self->add_method($name => $constructor);
1149 $self->_add_inlined_method($constructor);
1153 sub _inline_destructor {
1154 my ( $self, %args ) = @_;
1156 ( exists $args{destructor_class} )
1157 || confess "The 'inline_destructor' option is present, but "
1158 . "no destructor class was specified";
1160 my $destructor_class = $args{destructor_class};
1162 Class::MOP::load_class($destructor_class);
1164 return unless $destructor_class->is_needed( $self );
1166 my $destructor = $destructor_class->new(
1169 package_name => $self->name,
1173 $self->add_method( 'DESTROY' => $destructor );
1175 $self->_add_inlined_method($destructor);
1186 Class::MOP::Class - Class Meta Object
1190 # assuming that class Foo
1191 # has been defined, you can
1193 # use this for introspection ...
1195 # add a method to Foo ...
1196 Foo->meta->add_method( 'bar' => sub {...} )
1198 # get a list of all the classes searched
1199 # the method dispatcher in the correct order
1200 Foo->meta->class_precedence_list()
1202 # remove a method from Foo
1203 Foo->meta->remove_method('bar');
1205 # or use this to actually create classes ...
1207 Class::MOP::Class->create(
1210 superclasses => ['Foo'],
1212 Class::MOP:: : Attribute->new('$bar'),
1213 Class::MOP:: : Attribute->new('$baz'),
1216 calculate_bar => sub {...},
1217 construct_baz => sub {...}
1224 The Class Protocol is the largest and most complex part of the
1225 Class::MOP meta-object protocol. It controls the introspection and
1226 manipulation of Perl 5 classes, and it can create them as well. The
1227 best way to understand what this module can do, is to read the
1228 documentation for each of its methods.
1232 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1236 =head2 Class construction
1238 These methods all create new C<Class::MOP::Class> objects. These
1239 objects can represent existing classes, or they can be used to create
1240 new classes from scratch.
1242 The metaclass object for a given class is a singleton. If you attempt
1243 to create a metaclass for the same class twice, you will just get the
1248 =item B<< Class::MOP::Class->create($package_name, %options) >>
1250 This method creates a new C<Class::MOP::Class> object with the given
1251 package name. It accepts a number of options.
1257 An optional version number for the newly created package.
1261 An optional authority for the newly created package.
1263 =item * superclasses
1265 An optional array reference of superclass names.
1269 An optional hash reference of methods for the class. The keys of the
1270 hash reference are method names, and values are subroutine references.
1274 An optional array reference of attributes.
1276 An attribute can be passed as an existing L<Class::MOP::Attribute>
1277 object, I<or> or as a hash reference of options which will be passed
1278 to the attribute metaclass's constructor.
1282 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1284 This method works just like C<< Class::MOP::Class->create >> but it
1285 creates an "anonymous" class. In fact, the class does have a name, but
1286 that name is a unique name generated internally by this module.
1288 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1289 parameters that C<create> accepts.
1291 Anonymous classes are destroyed once the metaclass they are attached
1292 to goes out of scope, and will be removed from Perl's internal symbol
1295 All instances of an anonymous class keep a special reference to the
1296 metaclass object, which prevents the metaclass from going out of scope
1297 while any instances exist.
1299 This only works if the instance if based on a hash reference, however.
1301 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1303 This method will initialize a C<Class::MOP::Class> object for the
1304 named package. Unlike C<create>, this method I<will not> create a new
1307 The purpose of this method is to retrieve a C<Class::MOP::Class>
1308 object for introspecting an existing class.
1310 If an existing C<Class::MOP::Class> object exists for the named
1311 package, it will be returned, and any options provided will be
1314 If the object does not yet exist, it will be created.
1316 The valid options that can be passed to this method are
1317 C<attribute_metaclass>, C<method_metaclass>,
1318 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1319 optional, and default to the appropriate class in the C<Class::MOP>
1324 =head2 Object instance construction and cloning
1326 These methods are all related to creating and/or cloning object
1331 =item B<< $metaclass->clone_object($instance, %params) >>
1333 This method clones an existing object instance. Any parameters you
1334 provide are will override existing attribute values in the object.
1336 This is a convenience method for cloning an object instance, then
1337 blessing it into the appropriate package.
1339 You could implement a clone method in your class, using this method:
1342 my ($self, %params) = @_;
1343 $self->meta->clone_object($self, %params);
1346 =item B<< $metaclass->rebless_instance($instance, %params) >>
1348 This method changes the class of C<$instance> to the metaclass's class.
1350 You can only rebless an instance into a subclass of its current
1351 class. If you pass any additional parameters, these will be treated
1352 like constructor parameters and used to initialize the object's
1353 attributes. Any existing attributes that are already set will be
1356 Before reblessing the instance, this method will call
1357 C<rebless_instance_away> on the instance's current metaclass. This method
1358 will be passed the instance, the new metaclass, and any parameters
1359 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1360 does nothing; it is merely a hook.
1362 =item B<< $metaclass->new_object(%params) >>
1364 This method is used to create a new object of the metaclass's
1365 class. Any parameters you provide are used to initialize the
1366 instance's attributes.
1368 =item B<< $metaclass->instance_metaclass >>
1370 Returns the class name of the instance metaclass, see
1371 L<Class::MOP::Instance> for more information on the instance
1374 =item B<< $metaclass->get_meta_instance >>
1376 Returns an instance of the C<instance_metaclass> to be used in the
1377 construction of a new instance of the class.
1381 =head2 Informational predicates
1383 These are a few predicate methods for asking information about the
1388 =item B<< $metaclass->is_anon_class >>
1390 This returns true if the class was created by calling C<<
1391 Class::MOP::Class->create_anon_class >>.
1393 =item B<< $metaclass->is_mutable >>
1395 This returns true if the class is still mutable.
1397 =item B<< $metaclass->is_immutable >>
1399 This returns true if the class has been made immutable.
1401 =item B<< $metaclass->is_pristine >>
1403 A class is I<not> pristine if it has non-inherited attributes or if it
1404 has any generated methods.
1408 =head2 Inheritance Relationships
1412 =item B<< $metaclass->superclasses(@superclasses) >>
1414 This is a read-write accessor which represents the superclass
1415 relationships of the metaclass's class.
1417 This is basically sugar around getting and setting C<@ISA>.
1419 =item B<< $metaclass->class_precedence_list >>
1421 This returns a list of all of the class's ancestor classes. The
1422 classes are returned in method dispatch order.
1424 =item B<< $metaclass->linearized_isa >>
1426 This returns a list based on C<class_precedence_list> but with all
1429 =item B<< $metaclass->subclasses >>
1431 This returns a list of subclasses for this class.
1435 =head2 Method introspection and creation
1437 These methods allow you to introspect a class's methods, as well as
1438 add, remove, or change methods.
1440 Determining what is truly a method in a Perl 5 class requires some
1441 heuristics (aka guessing).
1443 Methods defined outside the package with a fully qualified name (C<sub
1444 Package::name { ... }>) will be included. Similarly, methods named
1445 with a fully qualified name using L<Sub::Name> are also included.
1447 However, we attempt to ignore imported functions.
1449 Ultimately, we are using heuristics to determine what truly is a
1450 method in a class, and these heuristics may get the wrong answer in
1451 some edge cases. However, for most "normal" cases the heuristics work
1456 =item B<< $metaclass->get_method($method_name) >>
1458 This will return a L<Class::MOP::Method> for the specified
1459 C<$method_name>. If the class does not have the specified method, it
1462 =item B<< $metaclass->has_method($method_name) >>
1464 Returns a boolean indicating whether or not the class defines the
1465 named method. It does not include methods inherited from parent
1468 =item B<< $metaclass->get_method_map >>
1470 Returns a hash reference representing the methods defined in this
1471 class. The keys are method names and the values are
1472 L<Class::MOP::Method> objects.
1474 =item B<< $metaclass->get_method_list >>
1476 This will return a list of method I<names> for all methods defined in
1479 =item B<< $metaclass->get_all_methods >>
1481 This will traverse the inheritance hierarchy and return a list of all
1482 the L<Class::MOP::Method> objects for this class and its parents.
1484 =item B<< $metaclass->find_method_by_name($method_name) >>
1486 This will return a L<Class::MOP::Method> for the specified
1487 C<$method_name>. If the class does not have the specified method, it
1490 Unlike C<get_method>, this method I<will> look for the named method in
1493 =item B<< $metaclass->get_all_method_names >>
1495 This will return a list of method I<names> for all of this class's
1496 methods, including inherited methods.
1498 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1500 This method looks for the named method in the class and all of its
1501 parents. It returns every matching method it finds in the inheritance
1502 tree, so it returns a list of methods.
1504 Each method is returned as a hash reference with three keys. The keys
1505 are C<name>, C<class>, and C<code>. The C<code> key has a
1506 L<Class::MOP::Method> object as its value.
1508 The list of methods is distinct.
1510 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1512 This method returns the first method in any superclass matching the
1513 given name. It is effectively the method that C<SUPER::$method_name>
1516 =item B<< $metaclass->add_method($method_name, $method) >>
1518 This method takes a method name and a subroutine reference, and adds
1519 the method to the class.
1521 The subroutine reference can be a L<Class::MOP::Method>, and you are
1522 strongly encouraged to pass a meta method object instead of a code
1523 reference. If you do so, that object gets stored as part of the
1524 class's method map directly. If not, the meta information will have to
1525 be recreated later, and may be incorrect.
1527 If you provide a method object, this method will clone that object if
1528 the object's package name does not match the class name. This lets us
1529 track the original source of any methods added from other classes
1530 (notably Moose roles).
1532 =item B<< $metaclass->remove_method($method_name) >>
1534 Remove the named method from the class. This method returns the
1535 L<Class::MOP::Method> object for the method.
1537 =item B<< $metaclass->method_metaclass >>
1539 Returns the class name of the method metaclass, see
1540 L<Class::MOP::Method> for more information on the method metaclass.
1542 =item B<< $metaclass->wrapped_method_metaclass >>
1544 Returns the class name of the wrapped method metaclass, see
1545 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1550 =head2 Attribute introspection and creation
1552 Because Perl 5 does not have a core concept of attributes in classes,
1553 we can only return information about attributes which have been added
1554 via this class's methods. We cannot discover information about
1555 attributes which are defined in terms of "regular" Perl 5 methods.
1559 =item B<< $metaclass->get_attribute($attribute_name) >>
1561 This will return a L<Class::MOP::Attribute> for the specified
1562 C<$attribute_name>. If the class does not have the specified
1563 attribute, it returns C<undef>
1565 =item B<< $metaclass->has_attribute($attribute_name) >>
1567 Returns a boolean indicating whether or not the class defines the
1568 named attribute. It does not include attributes inherited from parent
1571 =item B<< $metaclass->get_attribute_map >>
1573 Returns a hash reference representing the attributes defined in this
1574 class. The keys are attribute names and the values are
1575 L<Class::MOP::Attribute> objects.
1577 =item B<< $metaclass->get_attribute_list >>
1579 This will return a list of attributes I<names> for all attributes
1580 defined in this class.
1582 =item B<< $metaclass->get_all_attributes >>
1584 This will traverse the inheritance hierarchy and return a list of all
1585 the L<Class::MOP::Attribute> objects for this class and its parents.
1587 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1589 This will return a L<Class::MOP::Attribute> for the specified
1590 C<$attribute_name>. If the class does not have the specified
1591 attribute, it returns C<undef>
1593 Unlike C<get_attribute>, this attribute I<will> look for the named
1594 attribute in superclasses.
1596 =item B<< $metaclass->add_attribute(...) >>
1598 This method accepts either an existing L<Class::MOP::Attribute>
1599 object, or parameters suitable for passing to that class's C<new>
1602 The attribute provided will be added to the class.
1604 Any accessor methods defined by the attribute will be added to the
1605 class when the attribute is added.
1607 If an attribute of the same name already exists, the old attribute
1608 will be removed first.
1610 =item B<< $metaclass->remove_attribute($attribute_name) >>
1612 This will remove the named attribute from the class, and
1613 L<Class::MOP::Attribute> object.
1615 Removing an attribute also removes any accessor methods defined by the
1618 However, note that removing an attribute will only affect I<future>
1619 object instances created for this class, not existing instances.
1621 =item B<< $metaclass->attribute_metaclass >>
1623 Returns the class name of the attribute metaclass for this class. By
1624 default, this is L<Class::MOP::Attribute>. for more information on
1628 =head2 Class Immutability
1630 Making a class immutable "freezes" the class definition. You can no
1631 longer call methods which alter the class, such as adding or removing
1632 methods or attributes.
1634 Making a class immutable lets us optimize the class by inlining some
1635 methods, and also allows us to optimize some methods on the metaclass
1638 The immutabilization system in L<Moose> takes much greater advantage
1639 of the inlining features than Class::MOP itself does.
1643 =item B<< $metaclass->make_immutable(%options) >>
1645 This method will create an immutable transformer and uses it to make
1646 the class and its metaclass object immutable.
1648 Details of how immutabilization works are in L<Class::MOP::Immutable>
1651 =item B<< $metaclass->make_mutable >>
1653 Calling this method reverse the immutabilization transformation.
1655 =item B<< $metaclass->immutable_transformer >>
1657 If the class has been made immutable previously, this returns the
1658 L<Class::MOP::Immutable> object that was created to do the
1661 If the class was never made immutable, this method will die.
1665 =head2 Method Modifiers
1667 Method modifiers are hooks which allow a method to be wrapped with
1668 I<before>, I<after> and I<around> method modifiers. Every time a
1669 method is called, it's modifiers are also called.
1671 A class can modify its own methods, as well as methods defined in
1674 =head3 How method modifiers work?
1676 Method modifiers work by wrapping the original method and then
1677 replacing it in the class's symbol table. The wrappers will handle
1678 calling all the modifiers in the appropriate order and preserving the
1679 calling context for the original method.
1681 The return values of C<before> and C<after> modifiers are
1682 ignored. This is because their purpose is B<not> to filter the input
1683 and output of the primary method (this is done with an I<around>
1686 This may seem like an odd restriction to some, but doing this allows
1687 for simple code to be added at the beginning or end of a method call
1688 without altering the function of the wrapped method or placing any
1689 extra responsibility on the code of the modifier.
1691 Of course if you have more complex needs, you can use the C<around>
1692 modifier which allows you to change both the parameters passed to the
1693 wrapped method, as well as its return value.
1695 Before and around modifiers are called in last-defined-first-called
1696 order, while after modifiers are called in first-defined-first-called
1697 order. So the call tree might looks something like this:
1709 =head3 What is the performance impact?
1711 Of course there is a performance cost associated with method
1712 modifiers, but we have made every effort to make that cost directly
1713 proportional to the number of modifier features you utilize.
1715 The wrapping method does it's best to B<only> do as much work as it
1716 absolutely needs to. In order to do this we have moved some of the
1717 performance costs to set-up time, where they are easier to amortize.
1719 All this said, our benchmarks have indicated the following:
1721 simple wrapper with no modifiers 100% slower
1722 simple wrapper with simple before modifier 400% slower
1723 simple wrapper with simple after modifier 450% slower
1724 simple wrapper with simple around modifier 500-550% slower
1725 simple wrapper with all 3 modifiers 1100% slower
1727 These numbers may seem daunting, but you must remember, every feature
1728 comes with some cost. To put things in perspective, just doing a
1729 simple C<AUTOLOAD> which does nothing but extract the name of the
1730 method called and return it costs about 400% over a normal method
1735 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
1737 This wraps the specified method with the supplied subroutine
1738 reference. The modifier will be called as a method itself, and will
1739 receive the same arguments as are passed to the method.
1741 When the modifier exits, the wrapped method will be called.
1743 The return value of the modifier will be ignored.
1745 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
1747 This wraps the specified method with the supplied subroutine
1748 reference. The modifier will be called as a method itself, and will
1749 receive the same arguments as are passed to the method.
1751 When the wrapped methods exits, the modifier will be called.
1753 The return value of the modifier will be ignored.
1755 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
1757 This wraps the specified method with the supplied subroutine
1760 The first argument passed to the modifier will be a subroutine
1761 reference to the wrapped method. The second argument is the object,
1762 and after that come any arguments passed when the method is called.
1764 The around modifier can choose to call the original method, as well as
1765 what arguments to pass if it does so.
1767 The return value of the modifier is what will be seen by the caller.
1771 =head2 Introspection
1775 =item B<< Class::MOP::Class->meta >>
1777 This will return a L<Class::MOP::Class> instance for this class.
1779 It should also be noted that L<Class::MOP> will actually bootstrap
1780 this module by installing a number of attribute meta-objects into its
1787 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1789 =head1 COPYRIGHT AND LICENSE
1791 Copyright 2006-2009 by Infinity Interactive, Inc.
1793 L<http://www.iinteractive.com>
1795 This library is free software; you can redistribute it and/or modify
1796 it under the same terms as Perl itself.