2 package Class::MOP::Class;
7 use Class::MOP::Instance;
8 use Class::MOP::Method::Wrapped;
11 use Scalar::Util 'blessed', 'reftype', 'weaken';
12 use Sub::Name 'subname';
13 use B 'svref_2object';
15 our $VERSION = '0.21';
16 our $AUTHORITY = 'cpan:STEVAN';
18 use base 'Class::MOP::Module';
22 sub meta { Class::MOP::Class->initialize(blessed($_[0]) || $_[0]) }
28 my $package_name = shift;
29 (defined $package_name && $package_name && !blessed($package_name))
30 || confess "You must pass a package name and it cannot be blessed";
31 $class->construct_class_instance(':package' => $package_name, @_);
36 my $package_name = shift;
37 (defined $package_name && $package_name && !blessed($package_name))
38 || confess "You must pass a package name and it cannot be blessed";
39 Class::MOP::remove_metaclass_by_name($package_name);
40 $class->construct_class_instance(':package' => $package_name, @_);
43 # NOTE: (meta-circularity)
44 # this is a special form of &construct_instance
45 # (see below), which is used to construct class
46 # meta-object instances for any Class::MOP::*
47 # class. All other classes will use the more
48 # normal &construct_instance.
49 sub construct_class_instance {
52 my $package_name = $options{':package'};
53 (defined $package_name && $package_name)
54 || confess "You must pass a package name";
56 # return the metaclass if we have it cached,
57 # and it is still defined (it has not been
58 # reaped by DESTROY yet, which can happen
59 # annoyingly enough during global destruction)
60 return Class::MOP::get_metaclass_by_name($package_name)
61 if Class::MOP::does_metaclass_exist($package_name);
64 # we need to deal with the possibility
65 # of class immutability here, and then
66 # get the name of the class appropriately
67 $class = (blessed($class)
68 ? ($class->is_immutable
69 ? $class->get_mutable_metaclass_name()
73 # now create the metaclass
75 if ($class =~ /^Class::MOP::Class$/) {
78 # inherited from Class::MOP::Package
79 '$:package' => $package_name,
82 # since the following attributes will
83 # actually be loaded from the symbol
84 # table, and actually bypass the instance
85 # entirely, we can just leave these things
86 # listed here for reference, because they
87 # should not actually have a value associated
89 '%:namespace' => \undef,
90 # inherited from Class::MOP::Module
91 '$:version' => \undef,
92 '$:authority' => \undef,
93 # defined in Class::MOP::Class
97 '$:attribute_metaclass' => $options{':attribute_metaclass'} || 'Class::MOP::Attribute',
98 '$:method_metaclass' => $options{':method_metaclass'} || 'Class::MOP::Method',
99 '$:instance_metaclass' => $options{':instance_metaclass'} || 'Class::MOP::Instance',
104 # it is safe to use meta here because
105 # class will always be a subclass of
106 # Class::MOP::Class, which defines meta
107 $meta = $class->meta->construct_instance(%options)
110 # and check the metaclass compatibility
111 $meta->check_metaclass_compatability();
113 Class::MOP::store_metaclass_by_name($package_name, $meta);
116 # we need to weaken any anon classes
117 # so that they can call DESTROY properly
118 Class::MOP::weaken_metaclass($package_name) if $meta->is_anon_class;
123 sub check_metaclass_compatability {
126 # this is always okay ...
127 return if blessed($self) eq 'Class::MOP::Class' &&
128 $self->instance_metaclass eq 'Class::MOP::Instance';
130 my @class_list = $self->class_precedence_list;
131 shift @class_list; # shift off $self->name
133 foreach my $class_name (@class_list) {
134 my $meta = Class::MOP::get_metaclass_by_name($class_name) || next;
137 # we need to deal with the possibility
138 # of class immutability here, and then
139 # get the name of the class appropriately
140 my $meta_type = ($meta->is_immutable
141 ? $meta->get_mutable_metaclass_name()
144 ($self->isa($meta_type))
145 || confess $self->name . "->meta => (" . (blessed($self)) . ")" .
146 " is not compatible with the " .
147 $class_name . "->meta => (" . ($meta_type) . ")";
149 # we also need to check that instance metaclasses
150 # are compatabile in the same the class.
151 ($self->instance_metaclass->isa($meta->instance_metaclass))
152 || confess $self->name . "->meta => (" . ($self->instance_metaclass) . ")" .
153 " is not compatible with the " .
154 $class_name . "->meta => (" . ($meta->instance_metaclass) . ")";
162 # this should be sufficient, if you have a
163 # use case where it is not, write a test and
165 my $ANON_CLASS_SERIAL = 0;
168 # we need a sufficiently annoying prefix
169 # this should suffice for now, this is
170 # used in a couple of places below, so
171 # need to put it up here for now.
172 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
176 no warnings 'uninitialized';
177 $self->name =~ /^$ANON_CLASS_PREFIX/ ? 1 : 0;
180 sub create_anon_class {
181 my ($class, %options) = @_;
182 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
183 return $class->create($package_name, %options);
187 # this will only get called for
188 # anon-classes, all other calls
189 # are assumed to occur during
190 # global destruction and so don't
191 # really need to be handled explicitly
194 no warnings 'uninitialized';
195 return unless $self->name =~ /^$ANON_CLASS_PREFIX/;
196 my ($serial_id) = ($self->name =~ /^$ANON_CLASS_PREFIX(\d+)/);
198 foreach my $key (keys %{$ANON_CLASS_PREFIX . $serial_id}) {
199 delete ${$ANON_CLASS_PREFIX . $serial_id}{$key};
201 delete ${'main::' . $ANON_CLASS_PREFIX}{$serial_id . '::'};
206 # creating classes with MOP ...
210 my $package_name = shift;
212 (defined $package_name && $package_name)
213 || confess "You must pass a package name";
216 || confess "You much pass all parameters as name => value pairs " .
217 "(I found an uneven number of params in \@_)";
221 my $code = "package $package_name;";
222 $code .= "\$$package_name\:\:VERSION = '" . $options{version} . "';"
223 if exists $options{version};
224 $code .= "\$$package_name\:\:AUTHORITY = '" . $options{authority} . "';"
225 if exists $options{authority};
228 confess "creation of $package_name failed : $@" if $@;
230 my $meta = $class->initialize($package_name);
232 $meta->add_method('meta' => sub {
233 $class->initialize(blessed($_[0]) || $_[0]);
236 $meta->superclasses(@{$options{superclasses}})
237 if exists $options{superclasses};
239 # process attributes first, so that they can
240 # install accessors, but locally defined methods
241 # can then overwrite them. It is maybe a little odd, but
242 # I think this should be the order of things.
243 if (exists $options{attributes}) {
244 foreach my $attr (@{$options{attributes}}) {
245 $meta->add_attribute($attr);
248 if (exists $options{methods}) {
249 foreach my $method_name (keys %{$options{methods}}) {
250 $meta->add_method($method_name, $options{methods}->{$method_name});
259 # all these attribute readers will be bootstrapped
260 # away in the Class::MOP bootstrap section
262 sub get_attribute_map { $_[0]->{'%:attributes'} }
263 sub attribute_metaclass { $_[0]->{'$:attribute_metaclass'} }
264 sub method_metaclass { $_[0]->{'$:method_metaclass'} }
265 sub instance_metaclass { $_[0]->{'$:instance_metaclass'} }
268 # this is a prime canidate for conversion to XS
271 my $map = $self->{'%:methods'};
273 my $class_name = $self->name;
274 my $method_metaclass = $self->method_metaclass;
276 foreach my $symbol ($self->list_all_package_symbols('CODE')) {
277 my $code = $self->get_package_symbol('&' . $symbol);
279 next if exists $map->{$symbol} &&
280 defined $map->{$symbol} &&
281 $map->{$symbol}->body == $code;
283 my $gv = svref_2object($code)->GV;
284 next if ($gv->STASH->NAME || '') ne $class_name &&
285 ($gv->NAME || '') ne '__ANON__';
287 $map->{$symbol} = $method_metaclass->wrap($code);
293 # Instance Construction & Cloning
298 # we need to protect the integrity of the
299 # Class::MOP::Class singletons here, so we
300 # delegate this to &construct_class_instance
301 # which will deal with the singletons
302 return $class->construct_class_instance(@_)
303 if $class->name->isa('Class::MOP::Class');
304 return $class->construct_instance(@_);
307 sub construct_instance {
308 my ($class, %params) = @_;
309 my $meta_instance = $class->get_meta_instance();
310 my $instance = $meta_instance->create_instance();
311 foreach my $attr ($class->compute_all_applicable_attributes()) {
312 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
317 sub get_meta_instance {
319 return $class->instance_metaclass->new(
321 $class->compute_all_applicable_attributes()
327 my $instance = shift;
328 (blessed($instance) && $instance->isa($class->name))
329 || confess "You must pass an instance ($instance) of the metaclass (" . $class->name . ")";
331 # we need to protect the integrity of the
332 # Class::MOP::Class singletons here, they
333 # should not be cloned.
334 return $instance if $instance->isa('Class::MOP::Class');
335 $class->clone_instance($instance, @_);
339 my ($class, $instance, %params) = @_;
341 || confess "You can only clone instances, \$self is not a blessed instance";
342 my $meta_instance = $class->get_meta_instance();
343 my $clone = $meta_instance->clone_instance($instance);
344 foreach my $key (keys %params) {
345 next unless $meta_instance->is_valid_slot($key);
346 $meta_instance->set_slot_value($clone, $key, $params{$key});
357 @{$self->get_package_symbol('@ISA')} = @supers;
359 # we need to check the metaclass
360 # compatability here so that we can
361 # be sure that the superclass is
362 # not potentially creating an issues
363 # we don't know about
364 $self->check_metaclass_compatability();
366 @{$self->get_package_symbol('@ISA')};
369 sub class_precedence_list {
372 # We need to check for ciruclar inheirtance here.
373 # This will do nothing if all is well, and blow
374 # up otherwise. Yes, it's an ugly hack, better
375 # suggestions are welcome.
376 { ($self->name || return)->isa('This is a test for circular inheritance') }
377 # ... and now back to our regularly scheduled program
381 $self->initialize($_)->class_precedence_list()
382 } $self->superclasses()
389 my ($self, $method_name, $method) = @_;
390 (defined $method_name && $method_name)
391 || confess "You must define a method name";
394 if (blessed($method)) {
395 $body = $method->body;
399 ('CODE' eq (reftype($body) || ''))
400 || confess "Your code block must be a CODE reference";
401 $method = $self->method_metaclass->wrap($body);
403 $self->get_method_map->{$method_name} = $method;
405 my $full_method_name = ($self->name . '::' . $method_name);
406 $self->add_package_symbol("&${method_name}" => subname $full_method_name => $body);
410 my $fetch_and_prepare_method = sub {
411 my ($self, $method_name) = @_;
413 my $method = $self->get_method($method_name);
414 # if we dont have local ...
416 # try to find the next method
417 $method = $self->find_next_method_by_name($method_name);
418 # die if it does not exist
420 || confess "The method '$method_name' is not found in the inherience hierarchy for class " . $self->name;
421 # and now make sure to wrap it
422 # even if it is already wrapped
423 # because we need a new sub ref
424 $method = Class::MOP::Method::Wrapped->wrap($method);
427 # now make sure we wrap it properly
428 $method = Class::MOP::Method::Wrapped->wrap($method)
429 unless $method->isa('Class::MOP::Method::Wrapped');
431 $self->add_method($method_name => $method);
435 sub add_before_method_modifier {
436 my ($self, $method_name, $method_modifier) = @_;
437 (defined $method_name && $method_name)
438 || confess "You must pass in a method name";
439 my $method = $fetch_and_prepare_method->($self, $method_name);
440 $method->add_before_modifier(subname ':before' => $method_modifier);
443 sub add_after_method_modifier {
444 my ($self, $method_name, $method_modifier) = @_;
445 (defined $method_name && $method_name)
446 || confess "You must pass in a method name";
447 my $method = $fetch_and_prepare_method->($self, $method_name);
448 $method->add_after_modifier(subname ':after' => $method_modifier);
451 sub add_around_method_modifier {
452 my ($self, $method_name, $method_modifier) = @_;
453 (defined $method_name && $method_name)
454 || confess "You must pass in a method name";
455 my $method = $fetch_and_prepare_method->($self, $method_name);
456 $method->add_around_modifier(subname ':around' => $method_modifier);
460 # the methods above used to be named like this:
461 # ${pkg}::${method}:(before|after|around)
462 # but this proved problematic when using one modifier
463 # to wrap multiple methods (something which is likely
464 # to happen pretty regularly IMO). So instead of naming
465 # it like this, I have chosen to just name them purely
466 # with their modifier names, like so:
467 # :(before|after|around)
468 # The fact is that in a stack trace, it will be fairly
469 # evident from the context what method they are attached
470 # to, and so don't need the fully qualified name.
474 my ($self, $method_name, $method) = @_;
475 (defined $method_name && $method_name)
476 || confess "You must define a method name";
478 my $body = (blessed($method) ? $method->body : $method);
479 ('CODE' eq (reftype($body) || ''))
480 || confess "Your code block must be a CODE reference";
482 $self->add_package_symbol("&${method_name}" => $body);
486 my ($self, $method_name) = @_;
487 (defined $method_name && $method_name)
488 || confess "You must define a method name";
490 return 0 unless exists $self->get_method_map->{$method_name};
495 my ($self, $method_name) = @_;
496 (defined $method_name && $method_name)
497 || confess "You must define a method name";
500 # I don't really need this here, because
501 # if the method_map is missing a key it
502 # will just return undef for me now
503 # return unless $self->has_method($method_name);
505 return $self->get_method_map->{$method_name};
509 my ($self, $method_name) = @_;
510 (defined $method_name && $method_name)
511 || confess "You must define a method name";
513 my $removed_method = $self->get_method($method_name);
516 $self->remove_package_symbol("&${method_name}");
517 delete $self->get_method_map->{$method_name};
518 } if defined $removed_method;
520 return $removed_method;
523 sub get_method_list {
525 keys %{$self->get_method_map};
528 sub find_method_by_name {
529 my ($self, $method_name) = @_;
530 (defined $method_name && $method_name)
531 || confess "You must define a method name to find";
532 # keep a record of what we have seen
533 # here, this will handle all the
534 # inheritence issues because we are
535 # using the &class_precedence_list
537 my @cpl = $self->class_precedence_list();
538 foreach my $class (@cpl) {
539 next if $seen_class{$class};
540 $seen_class{$class}++;
541 # fetch the meta-class ...
542 my $meta = $self->initialize($class);
543 return $meta->get_method($method_name)
544 if $meta->has_method($method_name);
549 sub compute_all_applicable_methods {
552 # keep a record of what we have seen
553 # here, this will handle all the
554 # inheritence issues because we are
555 # using the &class_precedence_list
556 my (%seen_class, %seen_method);
557 foreach my $class ($self->class_precedence_list()) {
558 next if $seen_class{$class};
559 $seen_class{$class}++;
560 # fetch the meta-class ...
561 my $meta = $self->initialize($class);
562 foreach my $method_name ($meta->get_method_list()) {
563 next if exists $seen_method{$method_name};
564 $seen_method{$method_name}++;
566 name => $method_name,
568 code => $meta->get_method($method_name)
575 sub find_all_methods_by_name {
576 my ($self, $method_name) = @_;
577 (defined $method_name && $method_name)
578 || confess "You must define a method name to find";
580 # keep a record of what we have seen
581 # here, this will handle all the
582 # inheritence issues because we are
583 # using the &class_precedence_list
585 foreach my $class ($self->class_precedence_list()) {
586 next if $seen_class{$class};
587 $seen_class{$class}++;
588 # fetch the meta-class ...
589 my $meta = $self->initialize($class);
591 name => $method_name,
593 code => $meta->get_method($method_name)
594 } if $meta->has_method($method_name);
599 sub find_next_method_by_name {
600 my ($self, $method_name) = @_;
601 (defined $method_name && $method_name)
602 || confess "You must define a method name to find";
603 # keep a record of what we have seen
604 # here, this will handle all the
605 # inheritence issues because we are
606 # using the &class_precedence_list
608 my @cpl = $self->class_precedence_list();
609 shift @cpl; # discard ourselves
610 foreach my $class (@cpl) {
611 next if $seen_class{$class};
612 $seen_class{$class}++;
613 # fetch the meta-class ...
614 my $meta = $self->initialize($class);
615 return $meta->get_method($method_name)
616 if $meta->has_method($method_name);
625 # either we have an attribute object already
626 # or we need to create one from the args provided
627 my $attribute = blessed($_[0]) ? $_[0] : $self->attribute_metaclass->new(@_);
628 # make sure it is derived from the correct type though
629 ($attribute->isa('Class::MOP::Attribute'))
630 || confess "Your attribute must be an instance of Class::MOP::Attribute (or a subclass)";
632 # first we attach our new attribute
633 # because it might need certain information
634 # about the class which it is attached to
635 $attribute->attach_to_class($self);
637 # then we remove attributes of a conflicting
638 # name here so that we can properly detach
639 # the old attr object, and remove any
640 # accessors it would have generated
641 $self->remove_attribute($attribute->name)
642 if $self->has_attribute($attribute->name);
644 # then onto installing the new accessors
645 $attribute->install_accessors();
646 $self->get_attribute_map->{$attribute->name} = $attribute;
650 my ($self, $attribute_name) = @_;
651 (defined $attribute_name && $attribute_name)
652 || confess "You must define an attribute name";
653 exists $self->get_attribute_map->{$attribute_name} ? 1 : 0;
657 my ($self, $attribute_name) = @_;
658 (defined $attribute_name && $attribute_name)
659 || confess "You must define an attribute name";
660 return $self->get_attribute_map->{$attribute_name}
662 # this will return undef anyway, so no need ...
663 # if $self->has_attribute($attribute_name);
667 sub remove_attribute {
668 my ($self, $attribute_name) = @_;
669 (defined $attribute_name && $attribute_name)
670 || confess "You must define an attribute name";
671 my $removed_attribute = $self->get_attribute_map->{$attribute_name};
672 return unless defined $removed_attribute;
673 delete $self->get_attribute_map->{$attribute_name};
674 $removed_attribute->remove_accessors();
675 $removed_attribute->detach_from_class();
676 return $removed_attribute;
679 sub get_attribute_list {
681 keys %{$self->get_attribute_map};
684 sub compute_all_applicable_attributes {
687 # keep a record of what we have seen
688 # here, this will handle all the
689 # inheritence issues because we are
690 # using the &class_precedence_list
691 my (%seen_class, %seen_attr);
692 foreach my $class ($self->class_precedence_list()) {
693 next if $seen_class{$class};
694 $seen_class{$class}++;
695 # fetch the meta-class ...
696 my $meta = $self->initialize($class);
697 foreach my $attr_name ($meta->get_attribute_list()) {
698 next if exists $seen_attr{$attr_name};
699 $seen_attr{$attr_name}++;
700 push @attrs => $meta->get_attribute($attr_name);
706 sub find_attribute_by_name {
707 my ($self, $attr_name) = @_;
708 # keep a record of what we have seen
709 # here, this will handle all the
710 # inheritence issues because we are
711 # using the &class_precedence_list
713 foreach my $class ($self->class_precedence_list()) {
714 next if $seen_class{$class};
715 $seen_class{$class}++;
716 # fetch the meta-class ...
717 my $meta = $self->initialize($class);
718 return $meta->get_attribute($attr_name)
719 if $meta->has_attribute($attr_name);
727 sub is_immutable { 0 }
730 return Class::MOP::Class::Immutable->make_metaclass_immutable(@_);
741 Class::MOP::Class - Class Meta Object
745 # assuming that class Foo
746 # has been defined, you can
748 # use this for introspection ...
750 # add a method to Foo ...
751 Foo->meta->add_method('bar' => sub { ... })
753 # get a list of all the classes searched
754 # the method dispatcher in the correct order
755 Foo->meta->class_precedence_list()
757 # remove a method from Foo
758 Foo->meta->remove_method('bar');
760 # or use this to actually create classes ...
762 Class::MOP::Class->create('Bar' => (
764 superclasses => [ 'Foo' ],
766 Class::MOP:::Attribute->new('$bar'),
767 Class::MOP:::Attribute->new('$baz'),
770 calculate_bar => sub { ... },
771 construct_baz => sub { ... }
777 This is the largest and currently most complex part of the Perl 5
778 meta-object protocol. It controls the introspection and
779 manipulation of Perl 5 classes (and it can create them too). The
780 best way to understand what this module can do, is to read the
781 documentation for each of it's methods.
785 =head2 Self Introspection
791 This will return a B<Class::MOP::Class> instance which is related
792 to this class. Thereby allowing B<Class::MOP::Class> to actually
795 As with B<Class::MOP::Attribute>, B<Class::MOP> will actually
796 bootstrap this module by installing a number of attribute meta-objects
797 into it's metaclass. This will allow this class to reap all the benifits
798 of the MOP when subclassing it.
802 =head2 Class construction
804 These methods will handle creating B<Class::MOP::Class> objects,
805 which can be used to both create new classes, and analyze
806 pre-existing classes.
808 This module will internally store references to all the instances
809 you create with these methods, so that they do not need to be
810 created any more than nessecary. Basically, they are singletons.
814 =item B<create ($package_name,
815 version =E<gt> ?$version,
816 authority =E<gt> ?$authority,
817 superclasses =E<gt> ?@superclasses,
818 methods =E<gt> ?%methods,
819 attributes =E<gt> ?%attributes)>
821 This returns a B<Class::MOP::Class> object, bringing the specified
822 C<$package_name> into existence and adding any of the C<$version>,
823 C<$authority>, C<@superclasses>, C<%methods> and C<%attributes> to
826 =item B<create_anon_class (superclasses =E<gt> ?@superclasses,
827 methods =E<gt> ?%methods,
828 attributes =E<gt> ?%attributes)>
830 This will create an anonymous class, it works much like C<create> but
831 it does not need a C<$package_name>. Instead it will create a suitably
832 unique package name for you to stash things into.
834 =item B<initialize ($package_name, %options)>
836 This initializes and returns returns a B<Class::MOP::Class> object
837 for a given a C<$package_name>.
839 =item B<reinitialize ($package_name, %options)>
841 This removes the old metaclass, and creates a new one in it's place.
842 Do B<not> use this unless you really know what you are doing, it could
843 very easily make a very large mess of your program.
845 =item B<construct_class_instance (%options)>
847 This will construct an instance of B<Class::MOP::Class>, it is
848 here so that we can actually "tie the knot" for B<Class::MOP::Class>
849 to use C<construct_instance> once all the bootstrapping is done. This
850 method is used internally by C<initialize> and should never be called
851 from outside of that method really.
853 =item B<check_metaclass_compatability>
855 This method is called as the very last thing in the
856 C<construct_class_instance> method. This will check that the
857 metaclass you are creating is compatible with the metaclasses of all
858 your ancestors. For more inforamtion about metaclass compatibility
859 see the C<About Metaclass compatibility> section in L<Class::MOP>.
863 =head2 Object instance construction and cloning
865 These methods are B<entirely optional>, it is up to you whether you want
870 =item B<instance_metaclass>
872 =item B<get_meta_instance>
874 =item B<new_object (%params)>
876 This is a convience method for creating a new object of the class, and
877 blessing it into the appropriate package as well. Ideally your class
878 would call a C<new> this method like so:
881 my ($class, %param) = @_;
882 $class->meta->new_object(%params);
885 Of course the ideal place for this would actually be in C<UNIVERSAL::>
886 but that is considered bad style, so we do not do that.
888 =item B<construct_instance (%params)>
890 This method is used to construct an instace structure suitable for
891 C<bless>-ing into your package of choice. It works in conjunction
892 with the Attribute protocol to collect all applicable attributes.
894 This will construct and instance using a HASH ref as storage
895 (currently only HASH references are supported). This will collect all
896 the applicable attributes and layout out the fields in the HASH ref,
897 it will then initialize them using either use the corresponding key
898 in C<%params> or any default value or initializer found in the
899 attribute meta-object.
901 =item B<clone_object ($instance, %params)>
903 This is a convience method for cloning an object instance, then
904 blessing it into the appropriate package. This method will call
905 C<clone_instance>, which performs a shallow copy of the object,
906 see that methods documentation for more details. Ideally your
907 class would call a C<clone> this method like so:
910 my ($self, %param) = @_;
911 $self->meta->clone_object($self, %params);
914 Of course the ideal place for this would actually be in C<UNIVERSAL::>
915 but that is considered bad style, so we do not do that.
917 =item B<clone_instance($instance, %params)>
919 This method is a compliment of C<construct_instance> (which means if
920 you override C<construct_instance>, you need to override this one too),
921 and clones the instance shallowly.
923 The cloned structure returned is (like with C<construct_instance>) an
924 unC<bless>ed HASH reference, it is your responsibility to then bless
925 this cloned structure into the right class (which C<clone_object> will
928 As of 0.11, this method will clone the C<$instance> structure shallowly,
929 as opposed to the deep cloning implemented in prior versions. After much
930 thought, research and discussion, I have decided that anything but basic
931 shallow cloning is outside the scope of the meta-object protocol. I
932 think Yuval "nothingmuch" Kogman put it best when he said that cloning
933 is too I<context-specific> to be part of the MOP.
939 These are a few predicate methods for asking information about the class.
943 =item B<is_anon_class>
947 =item B<is_immutable>
951 =head2 Inheritance Relationships
955 =item B<superclasses (?@superclasses)>
957 This is a read-write attribute which represents the superclass
958 relationships of the class the B<Class::MOP::Class> instance is
959 associated with. Basically, it can get and set the C<@ISA> for you.
962 Perl will occasionally perform some C<@ISA> and method caching, if
963 you decide to change your superclass relationship at runtime (which
964 is quite insane and very much not recommened), then you should be
965 aware of this and the fact that this module does not make any
966 attempt to address this issue.
968 =item B<class_precedence_list>
970 This computes the a list of all the class's ancestors in the same order
971 in which method dispatch will be done. This is similair to
972 what B<Class::ISA::super_path> does, but we don't remove duplicate names.
980 =item B<get_method_map>
982 =item B<method_metaclass>
984 =item B<add_method ($method_name, $method)>
986 This will take a C<$method_name> and CODE reference to that
987 C<$method> and install it into the class's package.
990 This does absolutely nothing special to C<$method>
991 other than use B<Sub::Name> to make sure it is tagged with the
992 correct name, and therefore show up correctly in stack traces and
995 =item B<alias_method ($method_name, $method)>
997 This will take a C<$method_name> and CODE reference to that
998 C<$method> and alias the method into the class's package.
1001 Unlike C<add_method>, this will B<not> try to name the
1002 C<$method> using B<Sub::Name>, it only aliases the method in
1003 the class's package.
1005 =item B<has_method ($method_name)>
1007 This just provides a simple way to check if the class implements
1008 a specific C<$method_name>. It will I<not> however, attempt to check
1009 if the class inherits the method (use C<UNIVERSAL::can> for that).
1011 This will correctly handle functions defined outside of the package
1012 that use a fully qualified name (C<sub Package::name { ... }>).
1014 This will correctly handle functions renamed with B<Sub::Name> and
1015 installed using the symbol tables. However, if you are naming the
1016 subroutine outside of the package scope, you must use the fully
1017 qualified name, including the package name, for C<has_method> to
1018 correctly identify it.
1020 This will attempt to correctly ignore functions imported from other
1021 packages using B<Exporter>. It breaks down if the function imported
1022 is an C<__ANON__> sub (such as with C<use constant>), which very well
1023 may be a valid method being applied to the class.
1025 In short, this method cannot always be trusted to determine if the
1026 C<$method_name> is actually a method. However, it will DWIM about
1027 90% of the time, so it's a small trade off I think.
1029 =item B<get_method ($method_name)>
1031 This will return a Class::MOP::Method instance related to the specified
1032 C<$method_name>, or return undef if that method does not exist.
1034 The Class::MOP::Method is codifiable, so you can use it like a normal
1035 CODE reference, see L<Class::MOP::Method> for more information.
1037 =item B<find_method_by_name ($method_name>
1039 This will return a CODE reference of the specified C<$method_name>,
1040 or return undef if that method does not exist.
1042 Unlike C<get_method> this will also look in the superclasses.
1044 =item B<remove_method ($method_name)>
1046 This will attempt to remove a given C<$method_name> from the class.
1047 It will return the CODE reference that it has removed, and will
1048 attempt to use B<Sub::Name> to clear the methods associated name.
1050 =item B<get_method_list>
1052 This will return a list of method names for all I<locally> defined
1053 methods. It does B<not> provide a list of all applicable methods,
1054 including any inherited ones. If you want a list of all applicable
1055 methods, use the C<compute_all_applicable_methods> method.
1057 =item B<compute_all_applicable_methods>
1059 This will return a list of all the methods names this class will
1060 respond to, taking into account inheritance. The list will be a list of
1061 HASH references, each one containing the following information; method
1062 name, the name of the class in which the method lives and a CODE
1063 reference for the actual method.
1065 =item B<find_all_methods_by_name ($method_name)>
1067 This will traverse the inheritence hierarchy and locate all methods
1068 with a given C<$method_name>. Similar to
1069 C<compute_all_applicable_methods> it returns a list of HASH references
1070 with the following information; method name (which will always be the
1071 same as C<$method_name>), the name of the class in which the method
1072 lives and a CODE reference for the actual method.
1074 The list of methods produced is a distinct list, meaning there are no
1075 duplicates in it. This is especially useful for things like object
1076 initialization and destruction where you only want the method called
1077 once, and in the correct order.
1079 =item B<find_next_method_by_name ($method_name)>
1081 This will return the first method to match a given C<$method_name> in
1082 the superclasses, this is basically equivalent to calling
1083 C<SUPER::$method_name>, but it can be dispatched at runtime.
1087 =head2 Method Modifiers
1089 Method modifiers are a concept borrowed from CLOS, in which a method
1090 can be wrapped with I<before>, I<after> and I<around> method modifiers
1091 that will be called everytime the method is called.
1093 =head3 How method modifiers work?
1095 Method modifiers work by wrapping the original method and then replacing
1096 it in the classes symbol table. The wrappers will handle calling all the
1097 modifiers in the appropariate orders and preserving the calling context
1098 for the original method.
1100 Each method modifier serves a particular purpose, which may not be
1101 obvious to users of other method wrapping modules. To start with, the
1102 return values of I<before> and I<after> modifiers are ignored. This is
1103 because thier purpose is B<not> to filter the input and output of the
1104 primary method (this is done with an I<around> modifier). This may seem
1105 like an odd restriction to some, but doing this allows for simple code
1106 to be added at the begining or end of a method call without jeapordizing
1107 the normal functioning of the primary method or placing any extra
1108 responsibility on the code of the modifier. Of course if you have more
1109 complex needs, then use the I<around> modifier, which uses a variation
1110 of continutation passing style to allow for a high degree of flexibility.
1112 Before and around modifiers are called in last-defined-first-called order,
1113 while after modifiers are called in first-defined-first-called order. So
1114 the call tree might looks something like this:
1124 To see examples of using method modifiers, see the following examples
1125 included in the distribution; F<InstanceCountingClass>, F<Perl6Attribute>,
1126 F<AttributesWithHistory> and F<C3MethodDispatchOrder>. There is also a
1127 classic CLOS usage example in the test F<017_add_method_modifier.t>.
1129 =head3 What is the performance impact?
1131 Of course there is a performance cost associated with method modifiers,
1132 but we have made every effort to make that cost be directly proportional
1133 to the amount of modifier features you utilize.
1135 The wrapping method does it's best to B<only> do as much work as it
1136 absolutely needs to. In order to do this we have moved some of the
1137 performance costs to set-up time, where they are easier to amortize.
1139 All this said, my benchmarks have indicated the following:
1141 simple wrapper with no modifiers 100% slower
1142 simple wrapper with simple before modifier 400% slower
1143 simple wrapper with simple after modifier 450% slower
1144 simple wrapper with simple around modifier 500-550% slower
1145 simple wrapper with all 3 modifiers 1100% slower
1147 These numbers may seem daunting, but you must remember, every feature
1148 comes with some cost. To put things in perspective, just doing a simple
1149 C<AUTOLOAD> which does nothing but extract the name of the method called
1150 and return it costs about 400% over a normal method call.
1154 =item B<add_before_method_modifier ($method_name, $code)>
1156 This will wrap the method at C<$method_name> and the supplied C<$code>
1157 will be passed the C<@_> arguments, and called before the original
1158 method is called. As specified above, the return value of the I<before>
1159 method modifiers is ignored, and it's ability to modify C<@_> is
1160 fairly limited. If you need to do either of these things, use an
1161 C<around> method modifier.
1163 =item B<add_after_method_modifier ($method_name, $code)>
1165 This will wrap the method at C<$method_name> so that the original
1166 method will be called, it's return values stashed, and then the
1167 supplied C<$code> will be passed the C<@_> arguments, and called.
1168 As specified above, the return value of the I<after> method
1169 modifiers is ignored, and it cannot modify the return values of
1170 the original method. If you need to do either of these things, use an
1171 C<around> method modifier.
1173 =item B<add_around_method_modifier ($method_name, $code)>
1175 This will wrap the method at C<$method_name> so that C<$code>
1176 will be called and passed the original method as an extra argument
1177 at the begining of the C<@_> argument list. This is a variation of
1178 continuation passing style, where the function prepended to C<@_>
1179 can be considered a continuation. It is up to C<$code> if it calls
1180 the original method or not, there is no restriction on what the
1181 C<$code> can or cannot do.
1187 It should be noted that since there is no one consistent way to define
1188 the attributes of a class in Perl 5. These methods can only work with
1189 the information given, and can not easily discover information on
1190 their own. See L<Class::MOP::Attribute> for more details.
1194 =item B<attribute_metaclass>
1196 =item B<get_attribute_map>
1198 =item B<add_attribute ($attribute_name, $attribute_meta_object)>
1200 This stores a C<$attribute_meta_object> in the B<Class::MOP::Class>
1201 instance associated with the given class, and associates it with
1202 the C<$attribute_name>. Unlike methods, attributes within the MOP
1203 are stored as meta-information only. They will be used later to
1204 construct instances from (see C<construct_instance> above).
1205 More details about the attribute meta-objects can be found in the
1206 L<Class::MOP::Attribute> or the L<Class::MOP/The Attribute protocol>
1209 It should be noted that any accessor, reader/writer or predicate
1210 methods which the C<$attribute_meta_object> has will be installed
1211 into the class at this time.
1214 If an attribute already exists for C<$attribute_name>, the old one
1215 will be removed (as well as removing all it's accessors), and then
1218 =item B<has_attribute ($attribute_name)>
1220 Checks to see if this class has an attribute by the name of
1221 C<$attribute_name> and returns a boolean.
1223 =item B<get_attribute ($attribute_name)>
1225 Returns the attribute meta-object associated with C<$attribute_name>,
1226 if none is found, it will return undef.
1228 =item B<remove_attribute ($attribute_name)>
1230 This will remove the attribute meta-object stored at
1231 C<$attribute_name>, then return the removed attribute meta-object.
1234 Removing an attribute will only affect future instances of
1235 the class, it will not make any attempt to remove the attribute from
1236 any existing instances of the class.
1238 It should be noted that any accessor, reader/writer or predicate
1239 methods which the attribute meta-object stored at C<$attribute_name>
1240 has will be removed from the class at this time. This B<will> make
1241 these attributes somewhat inaccessable in previously created
1242 instances. But if you are crazy enough to do this at runtime, then
1243 you are crazy enough to deal with something like this :).
1245 =item B<get_attribute_list>
1247 This returns a list of attribute names which are defined in the local
1248 class. If you want a list of all applicable attributes for a class,
1249 use the C<compute_all_applicable_attributes> method.
1251 =item B<compute_all_applicable_attributes>
1253 This will traverse the inheritance heirachy and return a list of all
1254 the applicable attributes for this class. It does not construct a
1255 HASH reference like C<compute_all_applicable_methods> because all
1256 that same information is discoverable through the attribute
1259 =item B<find_attribute_by_name ($attr_name)>
1261 This method will traverse the inheritance heirachy and find the
1262 first attribute whose name matches C<$attr_name>, then return it.
1263 It will return undef if nothing is found.
1267 =head2 Class closing
1271 =item B<make_immutable>
1277 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1279 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
1281 =head1 COPYRIGHT AND LICENSE
1283 Copyright 2006 by Infinity Interactive, Inc.
1285 L<http://www.iinteractive.com>
1287 This library is free software; you can redistribute it and/or modify
1288 it under the same terms as Perl itself.