2 package Class::MOP::Class;
8 use Scalar::Util 'blessed', 'reftype';
9 use Sub::Name 'subname';
10 use B 'svref_2object';
12 our $VERSION = '0.13';
14 use Class::MOP::Instance;
18 sub meta { Class::MOP::Class->initialize(blessed($_[0]) || $_[0]) }
23 # Metaclasses are singletons, so we cache them here.
24 # there is no need to worry about destruction though
25 # because they should die only when the program dies.
26 # After all, do package definitions even get reaped?
29 # means of accessing all the metaclasses that have
30 # been initialized thus far (for mugwumps obj browser)
31 sub get_all_metaclasses { %METAS }
32 sub get_all_metaclass_instances { values %METAS }
33 sub get_all_metaclass_names { keys %METAS }
37 my $package_name = shift;
38 (defined $package_name && $package_name && !blessed($package_name))
39 || confess "You must pass a package name and it cannot be blessed";
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 $METAS{$package_name}
61 if exists $METAS{$package_name} && defined $METAS{$package_name};
62 $class = blessed($class) || $class;
63 # now create the metaclass
65 if ($class =~ /^Class::MOP::/) {
67 '$:package' => $package_name,
69 '$:attribute_metaclass' => $options{':attribute_metaclass'} || 'Class::MOP::Attribute',
70 '$:method_metaclass' => $options{':method_metaclass'} || 'Class::MOP::Method',
75 # it is safe to use meta here because
76 # class will always be a subclass of
77 # Class::MOP::Class, which defines meta
78 $meta = bless $class->meta->construct_instance(%options) => $class
80 # and check the metaclass compatibility
81 $meta->check_metaclass_compatability();
82 $METAS{$package_name} = $meta;
85 sub check_metaclass_compatability {
88 # this is always okay ...
89 return if blessed($self) eq 'Class::MOP::Class';
91 my @class_list = $self->class_precedence_list;
92 shift @class_list; # shift off $self->name
94 foreach my $class_name (@class_list) {
95 my $meta = $METAS{$class_name} || next;
96 ($self->isa(blessed($meta)))
97 || confess $self->name . "->meta => (" . (blessed($self)) . ")" .
98 " is not compatible with the " .
99 $class_name . "->meta => (" . (blessed($meta)) . ")";
105 my ($class, $package_name, $package_version, %options) = @_;
106 (defined $package_name && $package_name)
107 || confess "You must pass a package name";
108 my $code = "package $package_name;";
109 $code .= "\$$package_name\:\:VERSION = '$package_version';"
110 if defined $package_version;
112 confess "creation of $package_name failed : $@" if $@;
113 my $meta = $class->initialize($package_name);
115 $meta->add_method('meta' => sub {
116 Class::MOP::Class->initialize(blessed($_[0]) || $_[0]);
119 $meta->superclasses(@{$options{superclasses}})
120 if exists $options{superclasses};
122 # process attributes first, so that they can
123 # install accessors, but locally defined methods
124 # can then overwrite them. It is maybe a little odd, but
125 # I think this should be the order of things.
126 if (exists $options{attributes}) {
127 foreach my $attr (@{$options{attributes}}) {
128 $meta->add_attribute($attr);
131 if (exists $options{methods}) {
132 foreach my $method_name (keys %{$options{methods}}) {
133 $meta->add_method($method_name, $options{methods}->{$method_name});
141 # this should be sufficient, if you have a
142 # use case where it is not, write a test and
144 my $ANON_CLASS_SERIAL = 0;
146 sub create_anon_class {
147 my ($class, %options) = @_;
148 my $package_name = 'Class::MOP::Class::__ANON__::SERIAL::' . ++$ANON_CLASS_SERIAL;
149 return $class->create($package_name, '0.00', %options);
156 # all these attribute readers will be bootstrapped
157 # away in the Class::MOP bootstrap section
159 sub name { $_[0]->{'$:package'} }
160 sub get_attribute_map { $_[0]->{'%:attributes'} }
161 sub attribute_metaclass { $_[0]->{'$:attribute_metaclass'} }
162 sub method_metaclass { $_[0]->{'$:method_metaclass'} }
164 # Instance Construction & Cloning
169 # we need to protect the integrity of the
170 # Class::MOP::Class singletons here, so we
171 # delegate this to &construct_class_instance
172 # which will deal with the singletons
173 return $class->construct_class_instance(@_)
174 if $class->name->isa('Class::MOP::Class');
175 return $class->construct_instance(@_);
178 sub construct_instance {
179 my ($class, %params) = @_;
180 my $meta_instance = Class::MOP::Instance->new($class);
181 foreach my $attr ($class->compute_all_applicable_attributes()) {
182 $attr->initialize_instance_slot($class, $meta_instance, \%params);
184 return $meta_instance->get_instance;
189 my $instance = shift;
190 (blessed($instance) && $instance->isa($class->name))
191 || confess "You must pass an instance ($instance) of the metaclass (" . $class->name . ")";
193 # we need to protect the integrity of the
194 # Class::MOP::Class singletons here, they
195 # should not be cloned.
196 return $instance if $instance->isa('Class::MOP::Class');
197 bless $class->clone_instance($instance, @_) => blessed($instance);
201 my ($class, $instance, %params) = @_;
203 || confess "You can only clone instances, \$self is not a blessed instance";
204 my $clone = { %$instance, %params };
210 # &name should be here too, but it is above
211 # because it gets bootstrapped away
215 ${$self->get_package_variable('$VERSION')};
225 @{$self->name . '::ISA'} = @supers;
227 @{$self->name . '::ISA'};
230 sub class_precedence_list {
233 # We need to check for ciruclar inheirtance here.
234 # This will do nothing if all is well, and blow
235 # up otherwise. Yes, it's an ugly hack, better
236 # suggestions are welcome.
237 { ($self->name || return)->isa('This is a test for circular inheritance') }
238 # ... and now back to our regularly scheduled program
243 # we grab the metaclass from the %METAS
244 # hash here to save the initialize() call
245 # if we can, but it is not always possible
246 ($METAS{$_} || $self->initialize($_))->class_precedence_list()
247 } $self->superclasses()
254 my ($self, $method_name, $method) = @_;
255 (defined $method_name && $method_name)
256 || confess "You must define a method name";
257 # use reftype here to allow for blessed subs ...
258 ('CODE' eq (reftype($method) || ''))
259 || confess "Your code block must be a CODE reference";
260 my $full_method_name = ($self->name . '::' . $method_name);
262 $method = $self->method_metaclass->wrap($method) unless blessed($method);
265 no warnings 'redefine';
266 *{$full_method_name} = subname $full_method_name => $method;
270 my $fetch_and_prepare_method = sub {
271 my ($self, $method_name) = @_;
273 my $method = $self->get_method($method_name);
274 # if we dont have local ...
276 # make sure this method even exists ...
277 ($self->find_next_method_by_name($method_name))
278 || confess "The method '$method_name' is not found in the inherience hierarchy for this class";
279 # if so, then create a local which just
280 # calls the next applicable method ...
281 $self->add_method($method_name => sub {
282 $self->find_next_method_by_name($method_name)->(@_);
284 $method = $self->get_method($method_name);
287 # now make sure we wrap it properly
288 # (if it isnt already)
289 unless ($method->isa('Class::MOP::Method::Wrapped')) {
290 $method = Class::MOP::Method::Wrapped->wrap($method);
291 $self->add_method($method_name => $method);
296 sub add_before_method_modifier {
297 my ($self, $method_name, $method_modifier) = @_;
298 (defined $method_name && $method_name)
299 || confess "You must pass in a method name";
300 my $method = $fetch_and_prepare_method->($self, $method_name);
301 $method->add_before_modifier(subname ':before' => $method_modifier);
304 sub add_after_method_modifier {
305 my ($self, $method_name, $method_modifier) = @_;
306 (defined $method_name && $method_name)
307 || confess "You must pass in a method name";
308 my $method = $fetch_and_prepare_method->($self, $method_name);
309 $method->add_after_modifier(subname ':after' => $method_modifier);
312 sub add_around_method_modifier {
313 my ($self, $method_name, $method_modifier) = @_;
314 (defined $method_name && $method_name)
315 || confess "You must pass in a method name";
316 my $method = $fetch_and_prepare_method->($self, $method_name);
317 $method->add_around_modifier(subname ':around' => $method_modifier);
321 # the methods above used to be named like this:
322 # ${pkg}::${method}:(before|after|around)
323 # but this proved problematic when using one modifier
324 # to wrap multiple methods (something which is likely
325 # to happen pretty regularly IMO). So instead of naming
326 # it like this, I have chosen to just name them purely
327 # with their modifier names, like so:
328 # :(before|after|around)
329 # The fact is that in a stack trace, it will be fairly
330 # evident from the context what method they are attached
331 # to, and so don't need the fully qualified name.
335 my ($self, $method_name, $method) = @_;
336 (defined $method_name && $method_name)
337 || confess "You must define a method name";
338 # use reftype here to allow for blessed subs ...
339 ('CODE' eq (reftype($method) || ''))
340 || confess "Your code block must be a CODE reference";
341 my $full_method_name = ($self->name . '::' . $method_name);
343 $method = $self->method_metaclass->wrap($method) unless blessed($method);
346 no warnings 'redefine';
347 *{$full_method_name} = $method;
351 my ($self, $method_name) = @_;
352 (defined $method_name && $method_name)
353 || confess "You must define a method name";
355 my $sub_name = ($self->name . '::' . $method_name);
358 return 0 if !defined(&{$sub_name});
359 my $method = \&{$sub_name};
360 return 0 if (svref_2object($method)->GV->STASH->NAME || '') ne $self->name &&
361 (svref_2object($method)->GV->NAME || '') ne '__ANON__';
363 # at this point we are relatively sure
364 # it is our method, so we bless/wrap it
365 $self->method_metaclass->wrap($method) unless blessed($method);
370 my ($self, $method_name) = @_;
371 (defined $method_name && $method_name)
372 || confess "You must define a method name";
374 return unless $self->has_method($method_name);
377 return \&{$self->name . '::' . $method_name};
381 my ($self, $method_name) = @_;
382 (defined $method_name && $method_name)
383 || confess "You must define a method name";
385 my $removed_method = $self->get_method($method_name);
388 delete ${$self->name . '::'}{$method_name}
389 if defined $removed_method;
391 return $removed_method;
394 sub get_method_list {
397 grep { $self->has_method($_) } %{$self->name . '::'};
400 sub compute_all_applicable_methods {
403 # keep a record of what we have seen
404 # here, this will handle all the
405 # inheritence issues because we are
406 # using the &class_precedence_list
407 my (%seen_class, %seen_method);
408 foreach my $class ($self->class_precedence_list()) {
409 next if $seen_class{$class};
410 $seen_class{$class}++;
411 # fetch the meta-class ...
412 my $meta = $self->initialize($class);
413 foreach my $method_name ($meta->get_method_list()) {
414 next if exists $seen_method{$method_name};
415 $seen_method{$method_name}++;
417 name => $method_name,
419 code => $meta->get_method($method_name)
426 sub find_all_methods_by_name {
427 my ($self, $method_name) = @_;
428 (defined $method_name && $method_name)
429 || confess "You must define a method name to find";
431 # keep a record of what we have seen
432 # here, this will handle all the
433 # inheritence issues because we are
434 # using the &class_precedence_list
436 foreach my $class ($self->class_precedence_list()) {
437 next if $seen_class{$class};
438 $seen_class{$class}++;
439 # fetch the meta-class ...
440 my $meta = $self->initialize($class);
442 name => $method_name,
444 code => $meta->get_method($method_name)
445 } if $meta->has_method($method_name);
450 sub find_next_method_by_name {
451 my ($self, $method_name) = @_;
452 (defined $method_name && $method_name)
453 || confess "You must define a method name to find";
454 # keep a record of what we have seen
455 # here, this will handle all the
456 # inheritence issues because we are
457 # using the &class_precedence_list
459 my @cpl = $self->class_precedence_list();
460 shift @cpl; # discard ourselves
461 foreach my $class (@cpl) {
462 next if $seen_class{$class};
463 $seen_class{$class}++;
464 # fetch the meta-class ...
465 my $meta = $self->initialize($class);
466 return $meta->get_method($method_name)
467 if $meta->has_method($method_name);
476 # either we have an attribute object already
477 # or we need to create one from the args provided
478 my $attribute = blessed($_[0]) ? $_[0] : $self->attribute_metaclass->new(@_);
479 # make sure it is derived from the correct type though
480 ($attribute->isa('Class::MOP::Attribute'))
481 || confess "Your attribute must be an instance of Class::MOP::Attribute (or a subclass)";
482 $attribute->attach_to_class($self);
483 $attribute->install_accessors();
484 $self->get_attribute_map->{$attribute->name} = $attribute;
488 my ($self, $attribute_name) = @_;
489 (defined $attribute_name && $attribute_name)
490 || confess "You must define an attribute name";
491 exists $self->get_attribute_map->{$attribute_name} ? 1 : 0;
495 my ($self, $attribute_name) = @_;
496 (defined $attribute_name && $attribute_name)
497 || confess "You must define an attribute name";
499 # we used to say `if $self->has_attribute($attribute_name)`
500 # here, but since get_attribute is called so often, we
501 # eliminate the function call here
502 return $self->{'%:attributes'}->{$attribute_name}
503 if exists $self->{'%:attributes'}->{$attribute_name};
507 sub remove_attribute {
508 my ($self, $attribute_name) = @_;
509 (defined $attribute_name && $attribute_name)
510 || confess "You must define an attribute name";
511 my $removed_attribute = $self->get_attribute_map->{$attribute_name};
512 return unless defined $removed_attribute;
513 delete $self->get_attribute_map->{$attribute_name};
514 $removed_attribute->remove_accessors();
515 $removed_attribute->detach_from_class();
516 return $removed_attribute;
519 sub get_attribute_list {
522 # We don't use get_attribute_map here because
523 # we ask for the attribute list quite often
524 # in compute_all_applicable_attributes, so
525 # eliminating the function call helps
526 keys %{$self->{'%:attributes'}};
529 sub compute_all_applicable_attributes {
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
536 my (%seen_class, %seen_attr);
537 foreach my $class ($self->class_precedence_list()) {
538 next if $seen_class{$class};
539 $seen_class{$class}++;
540 # fetch the meta-class ...
542 # we grab the metaclass from the %METAS
543 # hash here to save the initialize() call
544 my $meta = $METAS{$class};
545 foreach my $attr_name ($meta->get_attribute_list()) {
546 next if exists $seen_attr{$attr_name};
547 $seen_attr{$attr_name}++;
548 push @attrs => $meta->get_attribute($attr_name);
554 sub find_attribute_by_name {
555 my ($self, $attr_name) = @_;
556 # keep a record of what we have seen
557 # here, this will handle all the
558 # inheritence issues because we are
559 # using the &class_precedence_list
561 foreach my $class ($self->class_precedence_list()) {
562 next if $seen_class{$class};
563 $seen_class{$class}++;
564 # fetch the meta-class ...
565 my $meta = $self->initialize($class);
566 return $meta->get_attribute($attr_name)
567 if $meta->has_attribute($attr_name);
574 sub add_package_variable {
575 my ($self, $variable, $initial_value) = @_;
576 (defined $variable && $variable =~ /^[\$\@\%]/)
577 || confess "variable name does not have a sigil";
579 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
580 if (defined $initial_value) {
582 *{$self->name . '::' . $name} = $initial_value;
588 # We HAVE to localize $@ or all
589 # hell breaks loose. It is not
590 # good, believe me, not good.
592 eval $sigil . $self->name . '::' . $name;
595 confess "Could not create package variable ($variable) because : $e" if $e;
599 sub has_package_variable {
600 my ($self, $variable) = @_;
601 (defined $variable && $variable =~ /^[\$\@\%]/)
602 || confess "variable name does not have a sigil";
603 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
605 defined ${$self->name . '::'}{$name} ? 1 : 0;
608 sub get_package_variable {
609 my ($self, $variable) = @_;
610 (defined $variable && $variable =~ /^[\$\@\%]/)
611 || confess "variable name does not have a sigil";
612 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
616 # We HAVE to localize $@ or all
617 # hell breaks loose. It is not
618 # good, believe me, not good.
620 $ref = eval '\\' . $sigil . $self->name . '::' . $name;
623 confess "Could not get the package variable ($variable) because : $e" if $e;
624 # if we didn't die, then we can return it
628 sub remove_package_variable {
629 my ($self, $variable) = @_;
630 (defined $variable && $variable =~ /^[\$\@\%]/)
631 || confess "variable name does not have a sigil";
632 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
634 delete ${$self->name . '::'}{$name};
645 Class::MOP::Class - Class Meta Object
649 # assuming that class Foo
650 # has been defined, you can
652 # use this for introspection ...
654 # add a method to Foo ...
655 Foo->meta->add_method('bar' => sub { ... })
657 # get a list of all the classes searched
658 # the method dispatcher in the correct order
659 Foo->meta->class_precedence_list()
661 # remove a method from Foo
662 Foo->meta->remove_method('bar');
664 # or use this to actually create classes ...
666 Class::MOP::Class->create('Bar' => '0.01' => (
667 superclasses => [ 'Foo' ],
669 Class::MOP:::Attribute->new('$bar'),
670 Class::MOP:::Attribute->new('$baz'),
673 calculate_bar => sub { ... },
674 construct_baz => sub { ... }
680 This is the largest and currently most complex part of the Perl 5
681 meta-object protocol. It controls the introspection and
682 manipulation of Perl 5 classes (and it can create them too). The
683 best way to understand what this module can do, is to read the
684 documentation for each of it's methods.
688 =head2 Self Introspection
694 This will return a B<Class::MOP::Class> instance which is related
695 to this class. Thereby allowing B<Class::MOP::Class> to actually
698 As with B<Class::MOP::Attribute>, B<Class::MOP> will actually
699 bootstrap this module by installing a number of attribute meta-objects
700 into it's metaclass. This will allow this class to reap all the benifits
701 of the MOP when subclassing it.
703 =item B<get_all_metaclasses>
705 This will return an hash of all the metaclass instances that have
706 been cached by B<Class::MOP::Class> keyed by the package name.
708 =item B<get_all_metaclass_instances>
710 This will return an array of all the metaclass instances that have
711 been cached by B<Class::MOP::Class>.
713 =item B<get_all_metaclass_names>
715 This will return an array of all the metaclass names that have
716 been cached by B<Class::MOP::Class>.
720 =head2 Class construction
722 These methods will handle creating B<Class::MOP::Class> objects,
723 which can be used to both create new classes, and analyze
724 pre-existing classes.
726 This module will internally store references to all the instances
727 you create with these methods, so that they do not need to be
728 created any more than nessecary. Basically, they are singletons.
732 =item B<create ($package_name, ?$package_version,
733 superclasses =E<gt> ?@superclasses,
734 methods =E<gt> ?%methods,
735 attributes =E<gt> ?%attributes)>
737 This returns a B<Class::MOP::Class> object, bringing the specified
738 C<$package_name> into existence and adding any of the
739 C<$package_version>, C<@superclasses>, C<%methods> and C<%attributes>
742 =item B<create_anon_class (superclasses =E<gt> ?@superclasses,
743 methods =E<gt> ?%methods,
744 attributes =E<gt> ?%attributes)>
746 This will create an anonymous class, it works much like C<create> but
747 it does not need a C<$package_name>. Instead it will create a suitably
748 unique package name for you to stash things into.
750 =item B<initialize ($package_name)>
752 This initializes and returns returns a B<Class::MOP::Class> object
753 for a given a C<$package_name>.
755 =item B<construct_class_instance (%options)>
757 This will construct an instance of B<Class::MOP::Class>, it is
758 here so that we can actually "tie the knot" for B<Class::MOP::Class>
759 to use C<construct_instance> once all the bootstrapping is done. This
760 method is used internally by C<initialize> and should never be called
761 from outside of that method really.
763 =item B<check_metaclass_compatability>
765 This method is called as the very last thing in the
766 C<construct_class_instance> method. This will check that the
767 metaclass you are creating is compatible with the metaclasses of all
768 your ancestors. For more inforamtion about metaclass compatibility
769 see the C<About Metaclass compatibility> section in L<Class::MOP>.
773 =head2 Object instance construction and cloning
775 These methods are B<entirely optional>, it is up to you whether you want
780 =item B<new_object (%params)>
782 This is a convience method for creating a new object of the class, and
783 blessing it into the appropriate package as well. Ideally your class
784 would call a C<new> this method like so:
787 my ($class, %param) = @_;
788 $class->meta->new_object(%params);
791 Of course the ideal place for this would actually be in C<UNIVERSAL::>
792 but that is considered bad style, so we do not do that.
794 =item B<construct_instance (%params)>
796 This method is used to construct an instace structure suitable for
797 C<bless>-ing into your package of choice. It works in conjunction
798 with the Attribute protocol to collect all applicable attributes.
800 This will construct and instance using a HASH ref as storage
801 (currently only HASH references are supported). This will collect all
802 the applicable attributes and layout out the fields in the HASH ref,
803 it will then initialize them using either use the corresponding key
804 in C<%params> or any default value or initializer found in the
805 attribute meta-object.
807 =item B<clone_object ($instance, %params)>
809 This is a convience method for cloning an object instance, then
810 blessing it into the appropriate package. This method will call
811 C<clone_instance>, which performs a shallow copy of the object,
812 see that methods documentation for more details. Ideally your
813 class would call a C<clone> this method like so:
816 my ($self, %param) = @_;
817 $self->meta->clone_object($self, %params);
820 Of course the ideal place for this would actually be in C<UNIVERSAL::>
821 but that is considered bad style, so we do not do that.
823 =item B<clone_instance($instance, %params)>
825 This method is a compliment of C<construct_instance> (which means if
826 you override C<construct_instance>, you need to override this one too),
827 and clones the instance shallowly.
829 The cloned structure returned is (like with C<construct_instance>) an
830 unC<bless>ed HASH reference, it is your responsibility to then bless
831 this cloned structure into the right class (which C<clone_object> will
834 As of 0.11, this method will clone the C<$instance> structure shallowly,
835 as opposed to the deep cloning implemented in prior versions. After much
836 thought, research and discussion, I have decided that anything but basic
837 shallow cloning is outside the scope of the meta-object protocol. I
838 think Yuval "nothingmuch" Kogman put it best when he said that cloning
839 is too I<context-specific> to be part of the MOP.
849 This is a read-only attribute which returns the package name for the
850 given B<Class::MOP::Class> instance.
854 This is a read-only attribute which returns the C<$VERSION> of the
855 package for the given B<Class::MOP::Class> instance.
859 =head2 Inheritance Relationships
863 =item B<superclasses (?@superclasses)>
865 This is a read-write attribute which represents the superclass
866 relationships of the class the B<Class::MOP::Class> instance is
867 associated with. Basically, it can get and set the C<@ISA> for you.
870 Perl will occasionally perform some C<@ISA> and method caching, if
871 you decide to change your superclass relationship at runtime (which
872 is quite insane and very much not recommened), then you should be
873 aware of this and the fact that this module does not make any
874 attempt to address this issue.
876 =item B<class_precedence_list>
878 This computes the a list of all the class's ancestors in the same order
879 in which method dispatch will be done. This is similair to
880 what B<Class::ISA::super_path> does, but we don't remove duplicate names.
888 =item B<method_metaclass>
890 =item B<add_method ($method_name, $method)>
892 This will take a C<$method_name> and CODE reference to that
893 C<$method> and install it into the class's package.
896 This does absolutely nothing special to C<$method>
897 other than use B<Sub::Name> to make sure it is tagged with the
898 correct name, and therefore show up correctly in stack traces and
901 =item B<alias_method ($method_name, $method)>
903 This will take a C<$method_name> and CODE reference to that
904 C<$method> and alias the method into the class's package.
907 Unlike C<add_method>, this will B<not> try to name the
908 C<$method> using B<Sub::Name>, it only aliases the method in
911 =item B<has_method ($method_name)>
913 This just provides a simple way to check if the class implements
914 a specific C<$method_name>. It will I<not> however, attempt to check
915 if the class inherits the method (use C<UNIVERSAL::can> for that).
917 This will correctly handle functions defined outside of the package
918 that use a fully qualified name (C<sub Package::name { ... }>).
920 This will correctly handle functions renamed with B<Sub::Name> and
921 installed using the symbol tables. However, if you are naming the
922 subroutine outside of the package scope, you must use the fully
923 qualified name, including the package name, for C<has_method> to
924 correctly identify it.
926 This will attempt to correctly ignore functions imported from other
927 packages using B<Exporter>. It breaks down if the function imported
928 is an C<__ANON__> sub (such as with C<use constant>), which very well
929 may be a valid method being applied to the class.
931 In short, this method cannot always be trusted to determine if the
932 C<$method_name> is actually a method. However, it will DWIM about
933 90% of the time, so it's a small trade off I think.
935 =item B<get_method ($method_name)>
937 This will return a CODE reference of the specified C<$method_name>,
938 or return undef if that method does not exist.
940 =item B<remove_method ($method_name)>
942 This will attempt to remove a given C<$method_name> from the class.
943 It will return the CODE reference that it has removed, and will
944 attempt to use B<Sub::Name> to clear the methods associated name.
946 =item B<get_method_list>
948 This will return a list of method names for all I<locally> defined
949 methods. It does B<not> provide a list of all applicable methods,
950 including any inherited ones. If you want a list of all applicable
951 methods, use the C<compute_all_applicable_methods> method.
953 =item B<compute_all_applicable_methods>
955 This will return a list of all the methods names this class will
956 respond to, taking into account inheritance. The list will be a list of
957 HASH references, each one containing the following information; method
958 name, the name of the class in which the method lives and a CODE
959 reference for the actual method.
961 =item B<find_all_methods_by_name ($method_name)>
963 This will traverse the inheritence hierarchy and locate all methods
964 with a given C<$method_name>. Similar to
965 C<compute_all_applicable_methods> it returns a list of HASH references
966 with the following information; method name (which will always be the
967 same as C<$method_name>), the name of the class in which the method
968 lives and a CODE reference for the actual method.
970 The list of methods produced is a distinct list, meaning there are no
971 duplicates in it. This is especially useful for things like object
972 initialization and destruction where you only want the method called
973 once, and in the correct order.
975 =item B<find_next_method_by_name ($method_name)>
977 This will return the first method to match a given C<$method_name> in
978 the superclasses, this is basically equivalent to calling
979 C<SUPER::$method_name>, but it can be dispatched at runtime.
983 =head2 Method Modifiers
985 Method modifiers are a concept borrowed from CLOS, in which a method
986 can be wrapped with I<before>, I<after> and I<around> method modifiers
987 that will be called everytime the method is called.
989 =head3 How method modifiers work?
991 Method modifiers work by wrapping the original method and then replacing
992 it in the classes symbol table. The wrappers will handle calling all the
993 modifiers in the appropariate orders and preserving the calling context
994 for the original method.
996 Each method modifier serves a particular purpose, which may not be
997 obvious to users of other method wrapping modules. To start with, the
998 return values of I<before> and I<after> modifiers are ignored. This is
999 because thier purpose is B<not> to filter the input and output of the
1000 primary method (this is done with an I<around> modifier). This may seem
1001 like an odd restriction to some, but doing this allows for simple code
1002 to be added at the begining or end of a method call without jeapordizing
1003 the normal functioning of the primary method or placing any extra
1004 responsibility on the code of the modifier. Of course if you have more
1005 complex needs, then use the I<around> modifier, which uses a variation
1006 of continutation passing style to allow for a high degree of flexibility.
1008 Before and around modifiers are called in last-defined-first-called order,
1009 while after modifiers are called in first-defined-first-called order. So
1010 the call tree might looks something like this:
1020 To see examples of using method modifiers, see the following examples
1021 included in the distribution; F<InstanceCountingClass>, F<Perl6Attribute>,
1022 F<AttributesWithHistory> and F<C3MethodDispatchOrder>. There is also a
1023 classic CLOS usage example in the test F<017_add_method_modifier.t>.
1025 =head3 What is the performance impact?
1027 Of course there is a performance cost associated with method modifiers,
1028 but we have made every effort to make that cost be directly proportional
1029 to the amount of modifier features you utilize.
1031 The wrapping method does it's best to B<only> do as much work as it
1032 absolutely needs to. In order to do this we have moved some of the
1033 performance costs to set-up time, where they are easier to amortize.
1035 All this said, my benchmarks have indicated the following:
1037 simple wrapper with no modifiers 100% slower
1038 simple wrapper with simple before modifier 400% slower
1039 simple wrapper with simple after modifier 450% slower
1040 simple wrapper with simple around modifier 500-550% slower
1041 simple wrapper with all 3 modifiers 1100% slower
1043 These numbers may seem daunting, but you must remember, every feature
1044 comes with some cost. To put things in perspective, just doing a simple
1045 C<AUTOLOAD> which does nothing but extract the name of the method called
1046 and return it costs about 400% over a normal method call.
1050 =item B<add_before_method_modifier ($method_name, $code)>
1052 This will wrap the method at C<$method_name> and the supplied C<$code>
1053 will be passed the C<@_> arguments, and called before the original
1054 method is called. As specified above, the return value of the I<before>
1055 method modifiers is ignored, and it's ability to modify C<@_> is
1056 fairly limited. If you need to do either of these things, use an
1057 C<around> method modifier.
1059 =item B<add_after_method_modifier ($method_name, $code)>
1061 This will wrap the method at C<$method_name> so that the original
1062 method will be called, it's return values stashed, and then the
1063 supplied C<$code> will be passed the C<@_> arguments, and called.
1064 As specified above, the return value of the I<after> method
1065 modifiers is ignored, and it cannot modify the return values of
1066 the original method. If you need to do either of these things, use an
1067 C<around> method modifier.
1069 =item B<add_around_method_modifier ($method_name, $code)>
1071 This will wrap the method at C<$method_name> so that C<$code>
1072 will be called and passed the original method as an extra argument
1073 at the begining of the C<@_> argument list. This is a variation of
1074 continuation passing style, where the function prepended to C<@_>
1075 can be considered a continuation. It is up to C<$code> if it calls
1076 the original method or not, there is no restriction on what the
1077 C<$code> can or cannot do.
1083 It should be noted that since there is no one consistent way to define
1084 the attributes of a class in Perl 5. These methods can only work with
1085 the information given, and can not easily discover information on
1086 their own. See L<Class::MOP::Attribute> for more details.
1090 =item B<attribute_metaclass>
1092 =item B<get_attribute_map>
1094 =item B<add_attribute ($attribute_name, $attribute_meta_object)>
1096 This stores a C<$attribute_meta_object> in the B<Class::MOP::Class>
1097 instance associated with the given class, and associates it with
1098 the C<$attribute_name>. Unlike methods, attributes within the MOP
1099 are stored as meta-information only. They will be used later to
1100 construct instances from (see C<construct_instance> above).
1101 More details about the attribute meta-objects can be found in the
1102 L<Class::MOP::Attribute> or the L<Class::MOP/The Attribute protocol>
1105 It should be noted that any accessor, reader/writer or predicate
1106 methods which the C<$attribute_meta_object> has will be installed
1107 into the class at this time.
1109 =item B<has_attribute ($attribute_name)>
1111 Checks to see if this class has an attribute by the name of
1112 C<$attribute_name> and returns a boolean.
1114 =item B<get_attribute ($attribute_name)>
1116 Returns the attribute meta-object associated with C<$attribute_name>,
1117 if none is found, it will return undef.
1119 =item B<remove_attribute ($attribute_name)>
1121 This will remove the attribute meta-object stored at
1122 C<$attribute_name>, then return the removed attribute meta-object.
1125 Removing an attribute will only affect future instances of
1126 the class, it will not make any attempt to remove the attribute from
1127 any existing instances of the class.
1129 It should be noted that any accessor, reader/writer or predicate
1130 methods which the attribute meta-object stored at C<$attribute_name>
1131 has will be removed from the class at this time. This B<will> make
1132 these attributes somewhat inaccessable in previously created
1133 instances. But if you are crazy enough to do this at runtime, then
1134 you are crazy enough to deal with something like this :).
1136 =item B<get_attribute_list>
1138 This returns a list of attribute names which are defined in the local
1139 class. If you want a list of all applicable attributes for a class,
1140 use the C<compute_all_applicable_attributes> method.
1142 =item B<compute_all_applicable_attributes>
1144 This will traverse the inheritance heirachy and return a list of all
1145 the applicable attributes for this class. It does not construct a
1146 HASH reference like C<compute_all_applicable_methods> because all
1147 that same information is discoverable through the attribute
1150 =item B<find_attribute_by_name ($attr_name)>
1152 This method will traverse the inheritance heirachy and find the
1153 first attribute whose name matches C<$attr_name>, then return it.
1154 It will return undef if nothing is found.
1158 =head2 Package Variables
1160 Since Perl's classes are built atop the Perl package system, it is
1161 fairly common to use package scoped variables for things like static
1162 class variables. The following methods are convience methods for
1163 the creation and inspection of package scoped variables.
1167 =item B<add_package_variable ($variable_name, ?$initial_value)>
1169 Given a C<$variable_name>, which must contain a leading sigil, this
1170 method will create that variable within the package which houses the
1171 class. It also takes an optional C<$initial_value>, which must be a
1172 reference of the same type as the sigil of the C<$variable_name>
1175 =item B<get_package_variable ($variable_name)>
1177 This will return a reference to the package variable in
1180 =item B<has_package_variable ($variable_name)>
1182 Returns true (C<1>) if there is a package variable defined for
1183 C<$variable_name>, and false (C<0>) otherwise.
1185 =item B<remove_package_variable ($variable_name)>
1187 This will attempt to remove the package variable at C<$variable_name>.
1193 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1195 =head1 COPYRIGHT AND LICENSE
1197 Copyright 2006 by Infinity Interactive, Inc.
1199 L<http://www.iinteractive.com>
1201 This library is free software; you can redistribute it and/or modify
1202 it under the same terms as Perl itself.