2 package Class::MOP::Class;
8 use Scalar::Util 'blessed', 'reftype', 'weaken';
9 use Sub::Name 'subname';
10 use B 'svref_2object';
12 our $VERSION = '0.15';
14 use base 'Class::MOP::Module';
16 use Class::MOP::Instance;
20 sub meta { Class::MOP::Class->initialize(blessed($_[0]) || $_[0]) }
25 # Metaclasses are singletons, so we cache them here.
26 # there is no need to worry about destruction though
27 # because they should die only when the program dies.
28 # After all, do package definitions even get reaped?
31 # means of accessing all the metaclasses that have
32 # been initialized thus far (for mugwumps obj browser)
33 sub get_all_metaclasses { %METAS }
34 sub get_all_metaclass_instances { values %METAS }
35 sub get_all_metaclass_names { keys %METAS }
39 my $package_name = shift;
40 (defined $package_name && $package_name && !blessed($package_name))
41 || confess "You must pass a package name and it cannot be blessed";
42 $class->construct_class_instance(':package' => $package_name, @_);
47 my $package_name = shift;
48 (defined $package_name && $package_name && !blessed($package_name))
49 || confess "You must pass a package name and it cannot be blessed";
50 $METAS{$package_name} = undef;
51 $class->construct_class_instance(':package' => $package_name, @_);
55 # we need a sufficiently annoying prefix
56 # this should suffice for now
57 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
61 # this should be sufficient, if you have a
62 # use case where it is not, write a test and
64 my $ANON_CLASS_SERIAL = 0;
66 sub create_anon_class {
67 my ($class, %options) = @_;
68 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
69 return $class->create($package_name, '0.00', %options);
73 # NOTE: (meta-circularity)
74 # this is a special form of &construct_instance
75 # (see below), which is used to construct class
76 # meta-object instances for any Class::MOP::*
77 # class. All other classes will use the more
78 # normal &construct_instance.
79 sub construct_class_instance {
82 my $package_name = $options{':package'};
83 (defined $package_name && $package_name)
84 || confess "You must pass a package name";
86 # return the metaclass if we have it cached,
87 # and it is still defined (it has not been
88 # reaped by DESTROY yet, which can happen
89 # annoyingly enough during global destruction)
90 return $METAS{$package_name}
91 if exists $METAS{$package_name} && defined $METAS{$package_name};
92 $class = blessed($class) || $class;
93 # now create the metaclass
95 if ($class =~ /^Class::MOP::/) {
97 '$:package' => $package_name,
99 '$:attribute_metaclass' => $options{':attribute_metaclass'} || 'Class::MOP::Attribute',
100 '$:method_metaclass' => $options{':method_metaclass'} || 'Class::MOP::Method',
101 '$:instance_metaclass' => $options{':instance_metaclass'} || 'Class::MOP::Instance',
106 # it is safe to use meta here because
107 # class will always be a subclass of
108 # Class::MOP::Class, which defines meta
109 $meta = $class->meta->construct_instance(%options)
111 # and check the metaclass compatibility
112 $meta->check_metaclass_compatability();
113 $METAS{$package_name} = $meta;
115 # we need to weaken any anon classes
116 # so that they can call DESTROY properly
117 weaken($METAS{$package_name})
118 if $package_name =~ /^$ANON_CLASS_PREFIX/;
123 # this will only get called for
124 # anon-classes, all other calls
125 # are assumed to occur during
126 # global destruction and so don't
127 # really need to be handled explicitly
130 return unless $self->name =~ /^$ANON_CLASS_PREFIX/;
131 my ($serial_id) = ($self->name =~ /^$ANON_CLASS_PREFIX(\d+)/);
133 foreach my $key (keys %{$ANON_CLASS_PREFIX . $serial_id}) {
134 delete ${$ANON_CLASS_PREFIX . $serial_id}{$key};
136 delete ${'main::' . $ANON_CLASS_PREFIX}{$serial_id . '::'};
139 sub check_metaclass_compatability {
142 # this is always okay ...
143 return if blessed($self) eq 'Class::MOP::Class' &&
144 $self->instance_metaclass eq 'Class::MOP::Instance';
146 my @class_list = $self->class_precedence_list;
147 shift @class_list; # shift off $self->name
149 foreach my $class_name (@class_list) {
150 my $meta = $METAS{$class_name} || next;
151 ($self->isa(blessed($meta)))
152 || confess $self->name . "->meta => (" . (blessed($self)) . ")" .
153 " is not compatible with the " .
154 $class_name . "->meta => (" . (blessed($meta)) . ")";
156 # we also need to check that instance metaclasses
157 # are compatabile in the same the class.
158 ($self->instance_metaclass->isa($meta->instance_metaclass))
159 || confess $self->name . "->meta => (" . ($self->instance_metaclass) . ")" .
160 " is not compatible with the " .
161 $class_name . "->meta => (" . ($meta->instance_metaclass) . ")";
167 my ($class, $package_name, $package_version, %options) = @_;
168 (defined $package_name && $package_name)
169 || confess "You must pass a package name";
170 my $code = "package $package_name;";
171 $code .= "\$$package_name\:\:VERSION = '$package_version';"
172 if defined $package_version;
174 confess "creation of $package_name failed : $@" if $@;
175 my $meta = $class->initialize($package_name);
177 $meta->add_method('meta' => sub {
178 $class->initialize(blessed($_[0]) || $_[0]);
181 $meta->superclasses(@{$options{superclasses}})
182 if exists $options{superclasses};
184 # process attributes first, so that they can
185 # install accessors, but locally defined methods
186 # can then overwrite them. It is maybe a little odd, but
187 # I think this should be the order of things.
188 if (exists $options{attributes}) {
189 foreach my $attr (@{$options{attributes}}) {
190 $meta->add_attribute($attr);
193 if (exists $options{methods}) {
194 foreach my $method_name (keys %{$options{methods}}) {
195 $meta->add_method($method_name, $options{methods}->{$method_name});
204 # all these attribute readers will be bootstrapped
205 # away in the Class::MOP bootstrap section
207 sub name { $_[0]->{'$:package'} }
208 sub get_attribute_map { $_[0]->{'%:attributes'} }
209 sub attribute_metaclass { $_[0]->{'$:attribute_metaclass'} }
210 sub method_metaclass { $_[0]->{'$:method_metaclass'} }
211 sub instance_metaclass { $_[0]->{'$:instance_metaclass'} }
213 # Instance Construction & Cloning
218 # we need to protect the integrity of the
219 # Class::MOP::Class singletons here, so we
220 # delegate this to &construct_class_instance
221 # which will deal with the singletons
222 return $class->construct_class_instance(@_)
223 if $class->name->isa('Class::MOP::Class');
224 return $class->construct_instance(@_);
227 sub construct_instance {
228 my ($class, %params) = @_;
229 my $meta_instance = $class->get_meta_instance();
230 my $instance = $meta_instance->create_instance();
231 foreach my $attr ($class->compute_all_applicable_attributes()) {
232 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
237 sub get_meta_instance {
239 return $class->instance_metaclass->new(
241 $class->compute_all_applicable_attributes()
247 my $instance = shift;
248 (blessed($instance) && $instance->isa($class->name))
249 || confess "You must pass an instance ($instance) of the metaclass (" . $class->name . ")";
251 # we need to protect the integrity of the
252 # Class::MOP::Class singletons here, they
253 # should not be cloned.
254 return $instance if $instance->isa('Class::MOP::Class');
255 $class->clone_instance($instance, @_);
259 my ($class, $instance, %params) = @_;
261 || confess "You can only clone instances, \$self is not a blessed instance";
262 my $meta_instance = $class->get_meta_instance();
263 my $clone = $meta_instance->clone_instance($instance);
264 foreach my $key (keys %params) {
265 next unless $meta_instance->is_valid_slot($key);
266 $meta_instance->set_slot_value($clone, $key, $params{$key});
273 # &name should be here too, but it is above
274 # because it gets bootstrapped away
278 ${$self->get_package_variable('$VERSION')};
288 @{$self->name . '::ISA'} = @supers;
290 # we need to check the metaclass
291 # compatability here so that we can
292 # be sure that the superclass is
293 # not potentially creating an issues
294 # we don't know about
295 $self->check_metaclass_compatability();
297 @{$self->name . '::ISA'};
300 sub class_precedence_list {
303 # We need to check for ciruclar inheirtance here.
304 # This will do nothing if all is well, and blow
305 # up otherwise. Yes, it's an ugly hack, better
306 # suggestions are welcome.
307 { ($self->name || return)->isa('This is a test for circular inheritance') }
308 # ... and now back to our regularly scheduled program
312 $self->initialize($_)->class_precedence_list()
313 } $self->superclasses()
320 my ($self, $method_name, $method) = @_;
321 (defined $method_name && $method_name)
322 || confess "You must define a method name";
323 # use reftype here to allow for blessed subs ...
324 ('CODE' eq (reftype($method) || ''))
325 || confess "Your code block must be a CODE reference";
326 my $full_method_name = ($self->name . '::' . $method_name);
328 $method = $self->method_metaclass->wrap($method) unless blessed($method);
331 no warnings 'redefine';
332 *{$full_method_name} = subname $full_method_name => $method;
336 my $fetch_and_prepare_method = sub {
337 my ($self, $method_name) = @_;
339 my $method = $self->get_method($method_name);
340 # if we dont have local ...
342 # try to find the next method
343 $method = $self->find_next_method_by_name($method_name);
344 # die if it does not exist
346 || confess "The method '$method_name' is not found in the inherience hierarchy for this class";
347 # and now make sure to wrap it
348 # even if it is already wrapped
349 # because we need a new sub ref
350 $method = Class::MOP::Method::Wrapped->wrap($method);
353 # now make sure we wrap it properly
354 $method = Class::MOP::Method::Wrapped->wrap($method)
355 unless $method->isa('Class::MOP::Method::Wrapped');
357 $self->add_method($method_name => $method);
361 sub add_before_method_modifier {
362 my ($self, $method_name, $method_modifier) = @_;
363 (defined $method_name && $method_name)
364 || confess "You must pass in a method name";
365 my $method = $fetch_and_prepare_method->($self, $method_name);
366 $method->add_before_modifier(subname ':before' => $method_modifier);
369 sub add_after_method_modifier {
370 my ($self, $method_name, $method_modifier) = @_;
371 (defined $method_name && $method_name)
372 || confess "You must pass in a method name";
373 my $method = $fetch_and_prepare_method->($self, $method_name);
374 $method->add_after_modifier(subname ':after' => $method_modifier);
377 sub add_around_method_modifier {
378 my ($self, $method_name, $method_modifier) = @_;
379 (defined $method_name && $method_name)
380 || confess "You must pass in a method name";
381 my $method = $fetch_and_prepare_method->($self, $method_name);
382 $method->add_around_modifier(subname ':around' => $method_modifier);
386 # the methods above used to be named like this:
387 # ${pkg}::${method}:(before|after|around)
388 # but this proved problematic when using one modifier
389 # to wrap multiple methods (something which is likely
390 # to happen pretty regularly IMO). So instead of naming
391 # it like this, I have chosen to just name them purely
392 # with their modifier names, like so:
393 # :(before|after|around)
394 # The fact is that in a stack trace, it will be fairly
395 # evident from the context what method they are attached
396 # to, and so don't need the fully qualified name.
400 my ($self, $method_name, $method) = @_;
401 (defined $method_name && $method_name)
402 || confess "You must define a method name";
403 # use reftype here to allow for blessed subs ...
404 ('CODE' eq (reftype($method) || ''))
405 || confess "Your code block must be a CODE reference";
406 my $full_method_name = ($self->name . '::' . $method_name);
408 $method = $self->method_metaclass->wrap($method) unless blessed($method);
411 no warnings 'redefine';
412 *{$full_method_name} = $method;
416 my ($self, $method_name) = @_;
417 (defined $method_name && $method_name)
418 || confess "You must define a method name";
420 my $sub_name = ($self->name . '::' . $method_name);
423 return 0 if !defined(&{$sub_name});
424 my $method = \&{$sub_name};
425 return 0 if (svref_2object($method)->GV->STASH->NAME || '') ne $self->name &&
426 (svref_2object($method)->GV->NAME || '') ne '__ANON__';
428 # at this point we are relatively sure
429 # it is our method, so we bless/wrap it
430 $self->method_metaclass->wrap($method) unless blessed($method);
435 my ($self, $method_name) = @_;
436 (defined $method_name && $method_name)
437 || confess "You must define a method name";
439 return unless $self->has_method($method_name);
442 return \&{$self->name . '::' . $method_name};
446 my ($self, $method_name) = @_;
447 (defined $method_name && $method_name)
448 || confess "You must define a method name";
450 my $removed_method = $self->get_method($method_name);
453 delete ${$self->name . '::'}{$method_name}
454 if defined $removed_method;
456 return $removed_method;
459 sub get_method_list {
462 grep { $self->has_method($_) } keys %{$self->name . '::'};
465 sub compute_all_applicable_methods {
468 # keep a record of what we have seen
469 # here, this will handle all the
470 # inheritence issues because we are
471 # using the &class_precedence_list
472 my (%seen_class, %seen_method);
473 foreach my $class ($self->class_precedence_list()) {
474 next if $seen_class{$class};
475 $seen_class{$class}++;
476 # fetch the meta-class ...
477 my $meta = $self->initialize($class);
478 foreach my $method_name ($meta->get_method_list()) {
479 next if exists $seen_method{$method_name};
480 $seen_method{$method_name}++;
482 name => $method_name,
484 code => $meta->get_method($method_name)
491 sub find_all_methods_by_name {
492 my ($self, $method_name) = @_;
493 (defined $method_name && $method_name)
494 || confess "You must define a method name to find";
496 # keep a record of what we have seen
497 # here, this will handle all the
498 # inheritence issues because we are
499 # using the &class_precedence_list
501 foreach my $class ($self->class_precedence_list()) {
502 next if $seen_class{$class};
503 $seen_class{$class}++;
504 # fetch the meta-class ...
505 my $meta = $self->initialize($class);
507 name => $method_name,
509 code => $meta->get_method($method_name)
510 } if $meta->has_method($method_name);
515 sub find_next_method_by_name {
516 my ($self, $method_name) = @_;
517 (defined $method_name && $method_name)
518 || confess "You must define a method name to find";
519 # keep a record of what we have seen
520 # here, this will handle all the
521 # inheritence issues because we are
522 # using the &class_precedence_list
524 my @cpl = $self->class_precedence_list();
525 shift @cpl; # discard ourselves
526 foreach my $class (@cpl) {
527 next if $seen_class{$class};
528 $seen_class{$class}++;
529 # fetch the meta-class ...
530 my $meta = $self->initialize($class);
531 return $meta->get_method($method_name)
532 if $meta->has_method($method_name);
541 # either we have an attribute object already
542 # or we need to create one from the args provided
543 my $attribute = blessed($_[0]) ? $_[0] : $self->attribute_metaclass->new(@_);
544 # make sure it is derived from the correct type though
545 ($attribute->isa('Class::MOP::Attribute'))
546 || confess "Your attribute must be an instance of Class::MOP::Attribute (or a subclass)";
547 $attribute->attach_to_class($self);
548 $attribute->install_accessors();
549 $self->get_attribute_map->{$attribute->name} = $attribute;
552 # in theory we have to tell everyone the slot structure may have changed
556 my ($self, $attribute_name) = @_;
557 (defined $attribute_name && $attribute_name)
558 || confess "You must define an attribute name";
559 exists $self->get_attribute_map->{$attribute_name} ? 1 : 0;
563 my ($self, $attribute_name) = @_;
564 (defined $attribute_name && $attribute_name)
565 || confess "You must define an attribute name";
566 return $self->get_attribute_map->{$attribute_name}
567 if $self->has_attribute($attribute_name);
571 sub remove_attribute {
572 my ($self, $attribute_name) = @_;
573 (defined $attribute_name && $attribute_name)
574 || confess "You must define an attribute name";
575 my $removed_attribute = $self->get_attribute_map->{$attribute_name};
576 return unless defined $removed_attribute;
577 delete $self->get_attribute_map->{$attribute_name};
578 $removed_attribute->remove_accessors();
579 $removed_attribute->detach_from_class();
580 return $removed_attribute;
583 sub get_attribute_list {
585 keys %{$self->get_attribute_map};
588 sub compute_all_applicable_attributes {
591 # keep a record of what we have seen
592 # here, this will handle all the
593 # inheritence issues because we are
594 # using the &class_precedence_list
595 my (%seen_class, %seen_attr);
596 foreach my $class ($self->class_precedence_list()) {
597 next if $seen_class{$class};
598 $seen_class{$class}++;
599 # fetch the meta-class ...
600 my $meta = $self->initialize($class);
601 foreach my $attr_name ($meta->get_attribute_list()) {
602 next if exists $seen_attr{$attr_name};
603 $seen_attr{$attr_name}++;
604 push @attrs => $meta->get_attribute($attr_name);
610 sub find_attribute_by_name {
611 my ($self, $attr_name) = @_;
612 # keep a record of what we have seen
613 # here, this will handle all the
614 # inheritence issues because we are
615 # using the &class_precedence_list
617 foreach my $class ($self->class_precedence_list()) {
618 next if $seen_class{$class};
619 $seen_class{$class}++;
620 # fetch the meta-class ...
621 my $meta = $self->initialize($class);
622 return $meta->get_attribute($attr_name)
623 if $meta->has_attribute($attr_name);
630 sub add_package_variable {
631 my ($self, $variable, $initial_value) = @_;
632 (defined $variable && $variable =~ /^[\$\@\%]/)
633 || confess "variable name does not have a sigil";
635 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
636 if (defined $initial_value) {
638 *{$self->name . '::' . $name} = $initial_value;
644 # We HAVE to localize $@ or all
645 # hell breaks loose. It is not
646 # good, believe me, not good.
648 eval $sigil . $self->name . '::' . $name;
651 confess "Could not create package variable ($variable) because : $e" if $e;
655 sub has_package_variable {
656 my ($self, $variable) = @_;
657 (defined $variable && $variable =~ /^[\$\@\%]/)
658 || confess "variable name does not have a sigil";
659 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
661 defined ${$self->name . '::'}{$name} ? 1 : 0;
664 sub get_package_variable {
665 my ($self, $variable) = @_;
666 (defined $variable && $variable =~ /^[\$\@\%]/)
667 || confess "variable name does not have a sigil";
668 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
672 # We HAVE to localize $@ or all
673 # hell breaks loose. It is not
674 # good, believe me, not good.
676 $ref = eval '\\' . $sigil . $self->name . '::' . $name;
679 confess "Could not get the package variable ($variable) because : $e" if $e;
680 # if we didn't die, then we can return it
684 sub remove_package_variable {
685 my ($self, $variable) = @_;
686 (defined $variable && $variable =~ /^[\$\@\%]/)
687 || confess "variable name does not have a sigil";
688 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
690 delete ${$self->name . '::'}{$name};
696 sub is_immutable { 0 }
700 return Class::MOP::Class::Immutable->make_metaclass_immutable($class);
711 Class::MOP::Class - Class Meta Object
715 # assuming that class Foo
716 # has been defined, you can
718 # use this for introspection ...
720 # add a method to Foo ...
721 Foo->meta->add_method('bar' => sub { ... })
723 # get a list of all the classes searched
724 # the method dispatcher in the correct order
725 Foo->meta->class_precedence_list()
727 # remove a method from Foo
728 Foo->meta->remove_method('bar');
730 # or use this to actually create classes ...
732 Class::MOP::Class->create('Bar' => '0.01' => (
733 superclasses => [ 'Foo' ],
735 Class::MOP:::Attribute->new('$bar'),
736 Class::MOP:::Attribute->new('$baz'),
739 calculate_bar => sub { ... },
740 construct_baz => sub { ... }
746 This is the largest and currently most complex part of the Perl 5
747 meta-object protocol. It controls the introspection and
748 manipulation of Perl 5 classes (and it can create them too). The
749 best way to understand what this module can do, is to read the
750 documentation for each of it's methods.
754 =head2 Self Introspection
760 This will return a B<Class::MOP::Class> instance which is related
761 to this class. Thereby allowing B<Class::MOP::Class> to actually
764 As with B<Class::MOP::Attribute>, B<Class::MOP> will actually
765 bootstrap this module by installing a number of attribute meta-objects
766 into it's metaclass. This will allow this class to reap all the benifits
767 of the MOP when subclassing it.
769 =item B<get_all_metaclasses>
771 This will return an hash of all the metaclass instances that have
772 been cached by B<Class::MOP::Class> keyed by the package name.
774 =item B<get_all_metaclass_instances>
776 This will return an array of all the metaclass instances that have
777 been cached by B<Class::MOP::Class>.
779 =item B<get_all_metaclass_names>
781 This will return an array of all the metaclass names that have
782 been cached by B<Class::MOP::Class>.
786 =head2 Class construction
788 These methods will handle creating B<Class::MOP::Class> objects,
789 which can be used to both create new classes, and analyze
790 pre-existing classes.
792 This module will internally store references to all the instances
793 you create with these methods, so that they do not need to be
794 created any more than nessecary. Basically, they are singletons.
798 =item B<create ($package_name, ?$package_version,
799 superclasses =E<gt> ?@superclasses,
800 methods =E<gt> ?%methods,
801 attributes =E<gt> ?%attributes)>
803 This returns a B<Class::MOP::Class> object, bringing the specified
804 C<$package_name> into existence and adding any of the
805 C<$package_version>, C<@superclasses>, C<%methods> and C<%attributes>
808 =item B<create_anon_class (superclasses =E<gt> ?@superclasses,
809 methods =E<gt> ?%methods,
810 attributes =E<gt> ?%attributes)>
812 This will create an anonymous class, it works much like C<create> but
813 it does not need a C<$package_name>. Instead it will create a suitably
814 unique package name for you to stash things into.
816 =item B<initialize ($package_name, %options)>
818 This initializes and returns returns a B<Class::MOP::Class> object
819 for a given a C<$package_name>.
821 =item B<reinitialize ($package_name, %options)>
823 This removes the old metaclass, and creates a new one in it's place.
824 Do B<not> use this unless you really know what you are doing, it could
825 very easily make a very large mess of your program.
827 =item B<construct_class_instance (%options)>
829 This will construct an instance of B<Class::MOP::Class>, it is
830 here so that we can actually "tie the knot" for B<Class::MOP::Class>
831 to use C<construct_instance> once all the bootstrapping is done. This
832 method is used internally by C<initialize> and should never be called
833 from outside of that method really.
835 =item B<check_metaclass_compatability>
837 This method is called as the very last thing in the
838 C<construct_class_instance> method. This will check that the
839 metaclass you are creating is compatible with the metaclasses of all
840 your ancestors. For more inforamtion about metaclass compatibility
841 see the C<About Metaclass compatibility> section in L<Class::MOP>.
845 =head2 Object instance construction and cloning
847 These methods are B<entirely optional>, it is up to you whether you want
852 =item B<instance_metaclass>
854 =item B<get_meta_instance>
856 =item B<new_object (%params)>
858 This is a convience method for creating a new object of the class, and
859 blessing it into the appropriate package as well. Ideally your class
860 would call a C<new> this method like so:
863 my ($class, %param) = @_;
864 $class->meta->new_object(%params);
867 Of course the ideal place for this would actually be in C<UNIVERSAL::>
868 but that is considered bad style, so we do not do that.
870 =item B<construct_instance (%params)>
872 This method is used to construct an instace structure suitable for
873 C<bless>-ing into your package of choice. It works in conjunction
874 with the Attribute protocol to collect all applicable attributes.
876 This will construct and instance using a HASH ref as storage
877 (currently only HASH references are supported). This will collect all
878 the applicable attributes and layout out the fields in the HASH ref,
879 it will then initialize them using either use the corresponding key
880 in C<%params> or any default value or initializer found in the
881 attribute meta-object.
883 =item B<clone_object ($instance, %params)>
885 This is a convience method for cloning an object instance, then
886 blessing it into the appropriate package. This method will call
887 C<clone_instance>, which performs a shallow copy of the object,
888 see that methods documentation for more details. Ideally your
889 class would call a C<clone> this method like so:
892 my ($self, %param) = @_;
893 $self->meta->clone_object($self, %params);
896 Of course the ideal place for this would actually be in C<UNIVERSAL::>
897 but that is considered bad style, so we do not do that.
899 =item B<clone_instance($instance, %params)>
901 This method is a compliment of C<construct_instance> (which means if
902 you override C<construct_instance>, you need to override this one too),
903 and clones the instance shallowly.
905 The cloned structure returned is (like with C<construct_instance>) an
906 unC<bless>ed HASH reference, it is your responsibility to then bless
907 this cloned structure into the right class (which C<clone_object> will
910 As of 0.11, this method will clone the C<$instance> structure shallowly,
911 as opposed to the deep cloning implemented in prior versions. After much
912 thought, research and discussion, I have decided that anything but basic
913 shallow cloning is outside the scope of the meta-object protocol. I
914 think Yuval "nothingmuch" Kogman put it best when he said that cloning
915 is too I<context-specific> to be part of the MOP.
925 This is a read-only attribute which returns the package name for the
926 given B<Class::MOP::Class> instance.
930 This is a read-only attribute which returns the C<$VERSION> of the
931 package for the given B<Class::MOP::Class> instance.
935 =head2 Inheritance Relationships
939 =item B<superclasses (?@superclasses)>
941 This is a read-write attribute which represents the superclass
942 relationships of the class the B<Class::MOP::Class> instance is
943 associated with. Basically, it can get and set the C<@ISA> for you.
946 Perl will occasionally perform some C<@ISA> and method caching, if
947 you decide to change your superclass relationship at runtime (which
948 is quite insane and very much not recommened), then you should be
949 aware of this and the fact that this module does not make any
950 attempt to address this issue.
952 =item B<class_precedence_list>
954 This computes the a list of all the class's ancestors in the same order
955 in which method dispatch will be done. This is similair to
956 what B<Class::ISA::super_path> does, but we don't remove duplicate names.
964 =item B<method_metaclass>
966 =item B<add_method ($method_name, $method)>
968 This will take a C<$method_name> and CODE reference to that
969 C<$method> and install it into the class's package.
972 This does absolutely nothing special to C<$method>
973 other than use B<Sub::Name> to make sure it is tagged with the
974 correct name, and therefore show up correctly in stack traces and
977 =item B<alias_method ($method_name, $method)>
979 This will take a C<$method_name> and CODE reference to that
980 C<$method> and alias the method into the class's package.
983 Unlike C<add_method>, this will B<not> try to name the
984 C<$method> using B<Sub::Name>, it only aliases the method in
987 =item B<has_method ($method_name)>
989 This just provides a simple way to check if the class implements
990 a specific C<$method_name>. It will I<not> however, attempt to check
991 if the class inherits the method (use C<UNIVERSAL::can> for that).
993 This will correctly handle functions defined outside of the package
994 that use a fully qualified name (C<sub Package::name { ... }>).
996 This will correctly handle functions renamed with B<Sub::Name> and
997 installed using the symbol tables. However, if you are naming the
998 subroutine outside of the package scope, you must use the fully
999 qualified name, including the package name, for C<has_method> to
1000 correctly identify it.
1002 This will attempt to correctly ignore functions imported from other
1003 packages using B<Exporter>. It breaks down if the function imported
1004 is an C<__ANON__> sub (such as with C<use constant>), which very well
1005 may be a valid method being applied to the class.
1007 In short, this method cannot always be trusted to determine if the
1008 C<$method_name> is actually a method. However, it will DWIM about
1009 90% of the time, so it's a small trade off I think.
1011 =item B<get_method ($method_name)>
1013 This will return a CODE reference of the specified C<$method_name>,
1014 or return undef if that method does not exist.
1016 =item B<remove_method ($method_name)>
1018 This will attempt to remove a given C<$method_name> from the class.
1019 It will return the CODE reference that it has removed, and will
1020 attempt to use B<Sub::Name> to clear the methods associated name.
1022 =item B<get_method_list>
1024 This will return a list of method names for all I<locally> defined
1025 methods. It does B<not> provide a list of all applicable methods,
1026 including any inherited ones. If you want a list of all applicable
1027 methods, use the C<compute_all_applicable_methods> method.
1029 =item B<compute_all_applicable_methods>
1031 This will return a list of all the methods names this class will
1032 respond to, taking into account inheritance. The list will be a list of
1033 HASH references, each one containing the following information; method
1034 name, the name of the class in which the method lives and a CODE
1035 reference for the actual method.
1037 =item B<find_all_methods_by_name ($method_name)>
1039 This will traverse the inheritence hierarchy and locate all methods
1040 with a given C<$method_name>. Similar to
1041 C<compute_all_applicable_methods> it returns a list of HASH references
1042 with the following information; method name (which will always be the
1043 same as C<$method_name>), the name of the class in which the method
1044 lives and a CODE reference for the actual method.
1046 The list of methods produced is a distinct list, meaning there are no
1047 duplicates in it. This is especially useful for things like object
1048 initialization and destruction where you only want the method called
1049 once, and in the correct order.
1051 =item B<find_next_method_by_name ($method_name)>
1053 This will return the first method to match a given C<$method_name> in
1054 the superclasses, this is basically equivalent to calling
1055 C<SUPER::$method_name>, but it can be dispatched at runtime.
1059 =head2 Method Modifiers
1061 Method modifiers are a concept borrowed from CLOS, in which a method
1062 can be wrapped with I<before>, I<after> and I<around> method modifiers
1063 that will be called everytime the method is called.
1065 =head3 How method modifiers work?
1067 Method modifiers work by wrapping the original method and then replacing
1068 it in the classes symbol table. The wrappers will handle calling all the
1069 modifiers in the appropariate orders and preserving the calling context
1070 for the original method.
1072 Each method modifier serves a particular purpose, which may not be
1073 obvious to users of other method wrapping modules. To start with, the
1074 return values of I<before> and I<after> modifiers are ignored. This is
1075 because thier purpose is B<not> to filter the input and output of the
1076 primary method (this is done with an I<around> modifier). This may seem
1077 like an odd restriction to some, but doing this allows for simple code
1078 to be added at the begining or end of a method call without jeapordizing
1079 the normal functioning of the primary method or placing any extra
1080 responsibility on the code of the modifier. Of course if you have more
1081 complex needs, then use the I<around> modifier, which uses a variation
1082 of continutation passing style to allow for a high degree of flexibility.
1084 Before and around modifiers are called in last-defined-first-called order,
1085 while after modifiers are called in first-defined-first-called order. So
1086 the call tree might looks something like this:
1096 To see examples of using method modifiers, see the following examples
1097 included in the distribution; F<InstanceCountingClass>, F<Perl6Attribute>,
1098 F<AttributesWithHistory> and F<C3MethodDispatchOrder>. There is also a
1099 classic CLOS usage example in the test F<017_add_method_modifier.t>.
1101 =head3 What is the performance impact?
1103 Of course there is a performance cost associated with method modifiers,
1104 but we have made every effort to make that cost be directly proportional
1105 to the amount of modifier features you utilize.
1107 The wrapping method does it's best to B<only> do as much work as it
1108 absolutely needs to. In order to do this we have moved some of the
1109 performance costs to set-up time, where they are easier to amortize.
1111 All this said, my benchmarks have indicated the following:
1113 simple wrapper with no modifiers 100% slower
1114 simple wrapper with simple before modifier 400% slower
1115 simple wrapper with simple after modifier 450% slower
1116 simple wrapper with simple around modifier 500-550% slower
1117 simple wrapper with all 3 modifiers 1100% slower
1119 These numbers may seem daunting, but you must remember, every feature
1120 comes with some cost. To put things in perspective, just doing a simple
1121 C<AUTOLOAD> which does nothing but extract the name of the method called
1122 and return it costs about 400% over a normal method call.
1126 =item B<add_before_method_modifier ($method_name, $code)>
1128 This will wrap the method at C<$method_name> and the supplied C<$code>
1129 will be passed the C<@_> arguments, and called before the original
1130 method is called. As specified above, the return value of the I<before>
1131 method modifiers is ignored, and it's ability to modify C<@_> is
1132 fairly limited. If you need to do either of these things, use an
1133 C<around> method modifier.
1135 =item B<add_after_method_modifier ($method_name, $code)>
1137 This will wrap the method at C<$method_name> so that the original
1138 method will be called, it's return values stashed, and then the
1139 supplied C<$code> will be passed the C<@_> arguments, and called.
1140 As specified above, the return value of the I<after> method
1141 modifiers is ignored, and it cannot modify the return values of
1142 the original method. If you need to do either of these things, use an
1143 C<around> method modifier.
1145 =item B<add_around_method_modifier ($method_name, $code)>
1147 This will wrap the method at C<$method_name> so that C<$code>
1148 will be called and passed the original method as an extra argument
1149 at the begining of the C<@_> argument list. This is a variation of
1150 continuation passing style, where the function prepended to C<@_>
1151 can be considered a continuation. It is up to C<$code> if it calls
1152 the original method or not, there is no restriction on what the
1153 C<$code> can or cannot do.
1159 It should be noted that since there is no one consistent way to define
1160 the attributes of a class in Perl 5. These methods can only work with
1161 the information given, and can not easily discover information on
1162 their own. See L<Class::MOP::Attribute> for more details.
1166 =item B<attribute_metaclass>
1168 =item B<get_attribute_map>
1170 =item B<add_attribute ($attribute_name, $attribute_meta_object)>
1172 This stores a C<$attribute_meta_object> in the B<Class::MOP::Class>
1173 instance associated with the given class, and associates it with
1174 the C<$attribute_name>. Unlike methods, attributes within the MOP
1175 are stored as meta-information only. They will be used later to
1176 construct instances from (see C<construct_instance> above).
1177 More details about the attribute meta-objects can be found in the
1178 L<Class::MOP::Attribute> or the L<Class::MOP/The Attribute protocol>
1181 It should be noted that any accessor, reader/writer or predicate
1182 methods which the C<$attribute_meta_object> has will be installed
1183 into the class at this time.
1185 =item B<has_attribute ($attribute_name)>
1187 Checks to see if this class has an attribute by the name of
1188 C<$attribute_name> and returns a boolean.
1190 =item B<get_attribute ($attribute_name)>
1192 Returns the attribute meta-object associated with C<$attribute_name>,
1193 if none is found, it will return undef.
1195 =item B<remove_attribute ($attribute_name)>
1197 This will remove the attribute meta-object stored at
1198 C<$attribute_name>, then return the removed attribute meta-object.
1201 Removing an attribute will only affect future instances of
1202 the class, it will not make any attempt to remove the attribute from
1203 any existing instances of the class.
1205 It should be noted that any accessor, reader/writer or predicate
1206 methods which the attribute meta-object stored at C<$attribute_name>
1207 has will be removed from the class at this time. This B<will> make
1208 these attributes somewhat inaccessable in previously created
1209 instances. But if you are crazy enough to do this at runtime, then
1210 you are crazy enough to deal with something like this :).
1212 =item B<get_attribute_list>
1214 This returns a list of attribute names which are defined in the local
1215 class. If you want a list of all applicable attributes for a class,
1216 use the C<compute_all_applicable_attributes> method.
1218 =item B<compute_all_applicable_attributes>
1220 This will traverse the inheritance heirachy and return a list of all
1221 the applicable attributes for this class. It does not construct a
1222 HASH reference like C<compute_all_applicable_methods> because all
1223 that same information is discoverable through the attribute
1226 =item B<find_attribute_by_name ($attr_name)>
1228 This method will traverse the inheritance heirachy and find the
1229 first attribute whose name matches C<$attr_name>, then return it.
1230 It will return undef if nothing is found.
1234 =head2 Package Variables
1236 Since Perl's classes are built atop the Perl package system, it is
1237 fairly common to use package scoped variables for things like static
1238 class variables. The following methods are convience methods for
1239 the creation and inspection of package scoped variables.
1243 =item B<add_package_variable ($variable_name, ?$initial_value)>
1245 Given a C<$variable_name>, which must contain a leading sigil, this
1246 method will create that variable within the package which houses the
1247 class. It also takes an optional C<$initial_value>, which must be a
1248 reference of the same type as the sigil of the C<$variable_name>
1251 =item B<get_package_variable ($variable_name)>
1253 This will return a reference to the package variable in
1256 =item B<has_package_variable ($variable_name)>
1258 Returns true (C<1>) if there is a package variable defined for
1259 C<$variable_name>, and false (C<0>) otherwise.
1261 =item B<remove_package_variable ($variable_name)>
1263 This will attempt to remove the package variable at C<$variable_name>.
1267 =head2 Class closing
1273 =item B<is_immutable>
1275 =item B<make_immutable>
1281 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1283 =head1 COPYRIGHT AND LICENSE
1285 Copyright 2006 by Infinity Interactive, Inc.
1287 L<http://www.iinteractive.com>
1289 This library is free software; you can redistribute it and/or modify
1290 it under the same terms as Perl itself.