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;
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 $class = "Class::MOP::Class::Immutable::" . ref($self);
1032 if ( Class::MOP::is_class_loaded($class) ) {
1035 my $meta = Class::MOP::Class->initialize($class);
1037 $meta->superclasses( $trait, ref($self) );
1039 $meta->make_immutable;
1045 sub _rebless_as_immutable {
1046 my ( $self, @args ) = @_;
1048 $self->{__immutable}{original_class} = ref $self;
1050 bless $self => $self->immutable_metaclass(@args);
1053 sub _remove_inlined_code {
1056 $self->remove_method($_->name) for $self->_inlined_methods;
1058 delete $self->{__immutable}{inlined_methods};
1061 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } };
1063 sub _add_inlined_method {
1064 my ( $self, $method ) = @_;
1066 push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1069 sub _initialize_immutable {
1070 my ( $self, %args ) = @_;
1072 $self->{__immutable}{options} = \%args;
1073 $self->_install_inlined_code(%args);
1076 sub _install_inlined_code {
1077 my ( $self, %args ) = @_;
1080 $self->_inline_accessors(%args) if $args{inline_accessors};
1081 $self->_inline_constructor(%args) if $args{inline_constructor};
1082 $self->_inline_destructor(%args) if $args{inline_destructor};
1085 sub _rebless_as_mutable {
1088 bless $self, $self->get_mutable_metaclass_name;
1093 sub _inline_accessors {
1096 foreach my $attr_name ( $self->get_attribute_list ) {
1097 $self->get_attribute($attr_name)->install_accessors(1);
1101 sub _inline_constructor {
1102 my ( $self, %args ) = @_;
1104 my $name = $args{constructor_name};
1106 #if ( my $existing = $self->name->can($args{constructor_name}) ) {
1107 # if ( refaddr($existing) == refaddr(\&Moose::Object::new) ) {
1109 unless ($args{replace_constructor}
1110 or !$self->has_method($name) ) {
1111 my $class = $self->name;
1112 warn "Not inlining a constructor for $class since it defines"
1113 . " its own constructor.\n"
1114 . "If you are certain you don't need to inline your"
1115 . " constructor, specify inline_constructor => 0 in your"
1116 . " call to $class->meta->make_immutable\n";
1120 my $constructor_class = $args{constructor_class};
1122 Class::MOP::load_class($constructor_class);
1124 my $constructor = $constructor_class->new(
1128 package_name => $self->name,
1132 if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1133 $self->add_method($name => $constructor);
1134 $self->_add_inlined_method($constructor);
1138 sub _inline_destructor {
1139 my ( $self, %args ) = @_;
1141 ( exists $args{destructor_class} )
1142 || confess "The 'inline_destructor' option is present, but "
1143 . "no destructor class was specified";
1145 my $destructor_class = $args{destructor_class};
1147 Class::MOP::load_class($destructor_class);
1149 return unless $destructor_class->is_needed( $self );
1151 my $destructor = $destructor_class->new(
1154 package_name => $self->name,
1158 $self->add_method( 'DESTROY' => $destructor );
1160 $self->_add_inlined_method($destructor);
1171 Class::MOP::Class - Class Meta Object
1175 # assuming that class Foo
1176 # has been defined, you can
1178 # use this for introspection ...
1180 # add a method to Foo ...
1181 Foo->meta->add_method( 'bar' => sub {...} )
1183 # get a list of all the classes searched
1184 # the method dispatcher in the correct order
1185 Foo->meta->class_precedence_list()
1187 # remove a method from Foo
1188 Foo->meta->remove_method('bar');
1190 # or use this to actually create classes ...
1192 Class::MOP::Class->create(
1195 superclasses => ['Foo'],
1197 Class::MOP:: : Attribute->new('$bar'),
1198 Class::MOP:: : Attribute->new('$baz'),
1201 calculate_bar => sub {...},
1202 construct_baz => sub {...}
1209 The Class Protocol is the largest and most complex part of the
1210 Class::MOP meta-object protocol. It controls the introspection and
1211 manipulation of Perl 5 classes, and it can create them as well. The
1212 best way to understand what this module can do, is to read the
1213 documentation for each of its methods.
1217 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1221 =head2 Class construction
1223 These methods all create new C<Class::MOP::Class> objects. These
1224 objects can represent existing classes, or they can be used to create
1225 new classes from scratch.
1227 The metaclass object for a given class is a singleton. If you attempt
1228 to create a metaclass for the same class twice, you will just get the
1233 =item B<< Class::MOP::Class->create($package_name, %options) >>
1235 This method creates a new C<Class::MOP::Class> object with the given
1236 package name. It accepts a number of options.
1242 An optional version number for the newly created package.
1246 An optional authority for the newly created package.
1248 =item * superclasses
1250 An optional array reference of superclass names.
1254 An optional hash reference of methods for the class. The keys of the
1255 hash reference are method names, and values are subroutine references.
1259 An optional array reference of attributes.
1261 An attribute can be passed as an existing L<Class::MOP::Attribute>
1262 object, I<or> or as a hash reference of options which will be passed
1263 to the attribute metaclass's constructor.
1267 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1269 This method works just like C<< Class::MOP::Class->create >> but it
1270 creates an "anonymous" class. In fact, the class does have a name, but
1271 that name is a unique name generated internally by this module.
1273 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1274 parameters that C<create> accepts.
1276 Anonymous classes are destroyed once the metaclass they are attached
1277 to goes out of scope, and will be removed from Perl's internal symbol
1280 All instances of an anonymous class keep a special reference to the
1281 metaclass object, which prevents the metaclass from going out of scope
1282 while any instances exist.
1284 This only works if the instance if based on a hash reference, however.
1286 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1288 This method will initialize a C<Class::MOP::Class> object for the
1289 named package. Unlike C<create>, this method I<will not> create a new
1292 The purpose of this method is to retrieve a C<Class::MOP::Class>
1293 object for introspecting an existing class.
1295 If an existing C<Class::MOP::Class> object exists for the named
1296 package, it will be returned, and any options provided will be
1299 If the object does not yet exist, it will be created.
1301 The valid options that can be passed to this method are
1302 C<attribute_metaclass>, C<method_metaclass>,
1303 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1304 optional, and default to the appropriate class in the C<Class::MOP>
1309 =head2 Object instance construction and cloning
1311 These methods are all related to creating and/or cloning object
1316 =item B<< $metaclass->clone_object($instance, %params) >>
1318 This method clones an existing object instance. Any parameters you
1319 provide are will override existing attribute values in the object.
1321 This is a convenience method for cloning an object instance, then
1322 blessing it into the appropriate package.
1324 You could implement a clone method in your class, using this method:
1327 my ($self, %params) = @_;
1328 $self->meta->clone_object($self, %params);
1331 =item B<< $metaclass->rebless_instance($instance, %params) >>
1333 This method changes the class of C<$instance> to the metaclass's class.
1335 You can only rebless an instance into a subclass of its current
1336 class. If you pass any additional parameters, these will be treated
1337 like constructor parameters and used to initialize the object's
1338 attributes. Any existing attributes that are already set will be
1341 Before reblessing the instance, this method will call
1342 C<rebless_instance_away> on the instance's current metaclass. This method
1343 will be passed the instance, the new metaclass, and any parameters
1344 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1345 does nothing; it is merely a hook.
1347 =item B<< $metaclass->new_object(%params) >>
1349 This method is used to create a new object of the metaclass's
1350 class. Any parameters you provide are used to initialize the
1351 instance's attributes.
1353 =item B<< $metaclass->instance_metaclass >>
1355 Returns the class name of the instance metaclass, see
1356 L<Class::MOP::Instance> for more information on the instance
1359 =item B<< $metaclass->get_meta_instance >>
1361 Returns an instance of the C<instance_metaclass> to be used in the
1362 construction of a new instance of the class.
1366 =head2 Informational predicates
1368 These are a few predicate methods for asking information about the
1373 =item B<< $metaclass->is_anon_class >>
1375 This returns true if the class was created by calling C<<
1376 Class::MOP::Class->create_anon_class >>.
1378 =item B<< $metaclass->is_mutable >>
1380 This returns true if the class is still mutable.
1382 =item B<< $metaclass->is_immutable >>
1384 This returns true if the class has been made immutable.
1386 =item B<< $metaclass->is_pristine >>
1388 A class is I<not> pristine if it has non-inherited attributes or if it
1389 has any generated methods.
1393 =head2 Inheritance Relationships
1397 =item B<< $metaclass->superclasses(@superclasses) >>
1399 This is a read-write accessor which represents the superclass
1400 relationships of the metaclass's class.
1402 This is basically sugar around getting and setting C<@ISA>.
1404 =item B<< $metaclass->class_precedence_list >>
1406 This returns a list of all of the class's ancestor classes. The
1407 classes are returned in method dispatch order.
1409 =item B<< $metaclass->linearized_isa >>
1411 This returns a list based on C<class_precedence_list> but with all
1414 =item B<< $metaclass->subclasses >>
1416 This returns a list of subclasses for this class.
1420 =head2 Method introspection and creation
1422 These methods allow you to introspect a class's methods, as well as
1423 add, remove, or change methods.
1425 Determining what is truly a method in a Perl 5 class requires some
1426 heuristics (aka guessing).
1428 Methods defined outside the package with a fully qualified name (C<sub
1429 Package::name { ... }>) will be included. Similarly, methods named
1430 with a fully qualified name using L<Sub::Name> are also included.
1432 However, we attempt to ignore imported functions.
1434 Ultimately, we are using heuristics to determine what truly is a
1435 method in a class, and these heuristics may get the wrong answer in
1436 some edge cases. However, for most "normal" cases the heuristics work
1441 =item B<< $metaclass->get_method($method_name) >>
1443 This will return a L<Class::MOP::Method> for the specified
1444 C<$method_name>. If the class does not have the specified method, it
1447 =item B<< $metaclass->has_method($method_name) >>
1449 Returns a boolean indicating whether or not the class defines the
1450 named method. It does not include methods inherited from parent
1453 =item B<< $metaclass->get_method_map >>
1455 Returns a hash reference representing the methods defined in this
1456 class. The keys are method names and the values are
1457 L<Class::MOP::Method> objects.
1459 =item B<< $metaclass->get_method_list >>
1461 This will return a list of method I<names> for all methods defined in
1464 =item B<< $metaclass->get_all_methods >>
1466 This will traverse the inheritance hierarchy and return a list of all
1467 the L<Class::MOP::Method> objects for this class and its parents.
1469 =item B<< $metaclass->find_method_by_name($method_name) >>
1471 This will return a L<Class::MOP::Method> for the specified
1472 C<$method_name>. If the class does not have the specified method, it
1475 Unlike C<get_method>, this method I<will> look for the named method in
1478 =item B<< $metaclass->get_all_method_names >>
1480 This will return a list of method I<names> for all of this class's
1481 methods, including inherited methods.
1483 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1485 This method looks for the named method in the class and all of its
1486 parents. It returns every matching method it finds in the inheritance
1487 tree, so it returns a list of methods.
1489 Each method is returned as a hash reference with three keys. The keys
1490 are C<name>, C<class>, and C<code>. The C<code> key has a
1491 L<Class::MOP::Method> object as its value.
1493 The list of methods is distinct.
1495 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1497 This method returns the first method in any superclass matching the
1498 given name. It is effectively the method that C<SUPER::$method_name>
1501 =item B<< $metaclass->add_method($method_name, $method) >>
1503 This method takes a method name and a subroutine reference, and adds
1504 the method to the class.
1506 The subroutine reference can be a L<Class::MOP::Method>, and you are
1507 strongly encouraged to pass a meta method object instead of a code
1508 reference. If you do so, that object gets stored as part of the
1509 class's method map directly. If not, the meta information will have to
1510 be recreated later, and may be incorrect.
1512 If you provide a method object, this method will clone that object if
1513 the object's package name does not match the class name. This lets us
1514 track the original source of any methods added from other classes
1515 (notably Moose roles).
1517 =item B<< $metaclass->remove_method($method_name) >>
1519 Remove the named method from the class. This method returns the
1520 L<Class::MOP::Method> object for the method.
1522 =item B<< $metaclass->method_metaclass >>
1524 Returns the class name of the method metaclass, see
1525 L<Class::MOP::Method> for more information on the method metaclass.
1527 =item B<< $metaclass->wrapped_method_metaclass >>
1529 Returns the class name of the wrapped method metaclass, see
1530 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1535 =head2 Attribute introspection and creation
1537 Because Perl 5 does not have a core concept of attributes in classes,
1538 we can only return information about attributes which have been added
1539 via this class's methods. We cannot discover information about
1540 attributes which are defined in terms of "regular" Perl 5 methods.
1544 =item B<< $metaclass->get_attribute($attribute_name) >>
1546 This will return a L<Class::MOP::Attribute> for the specified
1547 C<$attribute_name>. If the class does not have the specified
1548 attribute, it returns C<undef>
1550 =item B<< $metaclass->has_attribute($attribute_name) >>
1552 Returns a boolean indicating whether or not the class defines the
1553 named attribute. It does not include attributes inherited from parent
1556 =item B<< $metaclass->get_attribute_map >>
1558 Returns a hash reference representing the attributes defined in this
1559 class. The keys are attribute names and the values are
1560 L<Class::MOP::Attribute> objects.
1562 =item B<< $metaclass->get_attribute_list >>
1564 This will return a list of attributes I<names> for all attributes
1565 defined in this class.
1567 =item B<< $metaclass->get_all_attributes >>
1569 This will traverse the inheritance hierarchy and return a list of all
1570 the L<Class::MOP::Attribute> objects for this class and its parents.
1572 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1574 This will return a L<Class::MOP::Attribute> for the specified
1575 C<$attribute_name>. If the class does not have the specified
1576 attribute, it returns C<undef>
1578 Unlike C<get_attribute>, this attribute I<will> look for the named
1579 attribute in superclasses.
1581 =item B<< $metaclass->add_attribute(...) >>
1583 This method accepts either an existing L<Class::MOP::Attribute>
1584 object, or parameters suitable for passing to that class's C<new>
1587 The attribute provided will be added to the class.
1589 Any accessor methods defined by the attribute will be added to the
1590 class when the attribute is added.
1592 If an attribute of the same name already exists, the old attribute
1593 will be removed first.
1595 =item B<< $metaclass->remove_attribute($attribute_name) >>
1597 This will remove the named attribute from the class, and
1598 L<Class::MOP::Attribute> object.
1600 Removing an attribute also removes any accessor methods defined by the
1603 However, note that removing an attribute will only affect I<future>
1604 object instances created for this class, not existing instances.
1606 =item B<< $metaclass->attribute_metaclass >>
1608 Returns the class name of the attribute metaclass for this class. By
1609 default, this is L<Class::MOP::Attribute>. for more information on
1613 =head2 Class Immutability
1615 Making a class immutable "freezes" the class definition. You can no
1616 longer call methods which alter the class, such as adding or removing
1617 methods or attributes.
1619 Making a class immutable lets us optimize the class by inlining some
1620 methods, and also allows us to optimize some methods on the metaclass
1623 The immutabilization system in L<Moose> takes much greater advantage
1624 of the inlining features than Class::MOP itself does.
1628 =item B<< $metaclass->make_immutable(%options) >>
1630 This method will create an immutable transformer and uses it to make
1631 the class and its metaclass object immutable.
1633 Details of how immutabilization works are in L<Class::MOP::Immutable>
1636 =item B<< $metaclass->make_mutable >>
1638 Calling this method reverse the immutabilization transformation.
1640 =item B<< $metaclass->immutable_transformer >>
1642 If the class has been made immutable previously, this returns the
1643 L<Class::MOP::Immutable> object that was created to do the
1646 If the class was never made immutable, this method will die.
1650 =head2 Method Modifiers
1652 Method modifiers are hooks which allow a method to be wrapped with
1653 I<before>, I<after> and I<around> method modifiers. Every time a
1654 method is called, it's modifiers are also called.
1656 A class can modify its own methods, as well as methods defined in
1659 =head3 How method modifiers work?
1661 Method modifiers work by wrapping the original method and then
1662 replacing it in the class's symbol table. The wrappers will handle
1663 calling all the modifiers in the appropriate order and preserving the
1664 calling context for the original method.
1666 The return values of C<before> and C<after> modifiers are
1667 ignored. This is because their purpose is B<not> to filter the input
1668 and output of the primary method (this is done with an I<around>
1671 This may seem like an odd restriction to some, but doing this allows
1672 for simple code to be added at the beginning or end of a method call
1673 without altering the function of the wrapped method or placing any
1674 extra responsibility on the code of the modifier.
1676 Of course if you have more complex needs, you can use the C<around>
1677 modifier which allows you to change both the parameters passed to the
1678 wrapped method, as well as its return value.
1680 Before and around modifiers are called in last-defined-first-called
1681 order, while after modifiers are called in first-defined-first-called
1682 order. So the call tree might looks something like this:
1694 =head3 What is the performance impact?
1696 Of course there is a performance cost associated with method
1697 modifiers, but we have made every effort to make that cost directly
1698 proportional to the number of modifier features you utilize.
1700 The wrapping method does it's best to B<only> do as much work as it
1701 absolutely needs to. In order to do this we have moved some of the
1702 performance costs to set-up time, where they are easier to amortize.
1704 All this said, our benchmarks have indicated the following:
1706 simple wrapper with no modifiers 100% slower
1707 simple wrapper with simple before modifier 400% slower
1708 simple wrapper with simple after modifier 450% slower
1709 simple wrapper with simple around modifier 500-550% slower
1710 simple wrapper with all 3 modifiers 1100% slower
1712 These numbers may seem daunting, but you must remember, every feature
1713 comes with some cost. To put things in perspective, just doing a
1714 simple C<AUTOLOAD> which does nothing but extract the name of the
1715 method called and return it costs about 400% over a normal method
1720 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
1722 This wraps the specified method with the supplied subroutine
1723 reference. The modifier will be called as a method itself, and will
1724 receive the same arguments as are passed to the method.
1726 When the modifier exits, the wrapped method will be called.
1728 The return value of the modifier will be ignored.
1730 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
1732 This wraps the specified method with the supplied subroutine
1733 reference. The modifier will be called as a method itself, and will
1734 receive the same arguments as are passed to the method.
1736 When the wrapped methods exits, the modifier will be called.
1738 The return value of the modifier will be ignored.
1740 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
1742 This wraps the specified method with the supplied subroutine
1745 The first argument passed to the modifier will be a subroutine
1746 reference to the wrapped method. The second argument is the object,
1747 and after that come any arguments passed when the method is called.
1749 The around modifier can choose to call the original method, as well as
1750 what arguments to pass if it does so.
1752 The return value of the modifier is what will be seen by the caller.
1756 =head2 Introspection
1760 =item B<< Class::MOP::Class->meta >>
1762 This will return a L<Class::MOP::Class> instance for this class.
1764 It should also be noted that L<Class::MOP> will actually bootstrap
1765 this module by installing a number of attribute meta-objects into its
1772 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1774 =head1 COPYRIGHT AND LICENSE
1776 Copyright 2006-2009 by Infinity Interactive, Inc.
1778 L<http://www.iinteractive.com>
1780 This library is free software; you can redistribute it and/or modify
1781 it under the same terms as Perl itself.