release 0.20
[gitmo/Class-MOP.git] / lib / Class / MOP / Class.pm
CommitLineData
8b978dd5 1
2package Class::MOP::Class;
3
4use strict;
5use warnings;
6
7use Carp 'confess';
0882828e 8use Scalar::Util 'blessed', 'reftype';
8b978dd5 9use Sub::Name 'subname';
96ceced8 10use B 'svref_2object';
8b978dd5 11
d3cb0d4a 12our $VERSION = '0.06';
8b978dd5 13
aa448b16 14# Self-introspection
2eb717d5 15
aa448b16 16sub meta { Class::MOP::Class->initialize(blessed($_[0]) || $_[0]) }
2eb717d5 17
8b978dd5 18# Creation
19
bfe4d0fc 20{
21 # Metaclasses are singletons, so we cache them here.
22 # there is no need to worry about destruction though
23 # because they should die only when the program dies.
24 # After all, do package definitions even get reaped?
651955fb 25 my %METAS;
26
bfe4d0fc 27 sub initialize {
351bd7d4 28 my $class = shift;
29 my $package_name = shift;
22286063 30 (defined $package_name && $package_name && !blessed($package_name))
31 || confess "You must pass a package name and it cannot be blessed";
651955fb 32 $class->construct_class_instance(':package' => $package_name, @_);
727919c5 33 }
34
35 # NOTE: (meta-circularity)
36 # this is a special form of &construct_instance
37 # (see below), which is used to construct class
1a7ebbb3 38 # meta-object instances for any Class::MOP::*
39 # class. All other classes will use the more
40 # normal &construct_instance.
727919c5 41 sub construct_class_instance {
351bd7d4 42 my $class = shift;
651955fb 43 my %options = @_;
44 my $package_name = $options{':package'};
727919c5 45 (defined $package_name && $package_name)
651955fb 46 || confess "You must pass a package name";
47 return $METAS{$package_name} if exists $METAS{$package_name};
1a7ebbb3 48 $class = blessed($class) || $class;
550d56db 49 # now create the metaclass
50 my $meta;
1a7ebbb3 51 if ($class =~ /^Class::MOP::/) {
550d56db 52 $meta = bless {
351bd7d4 53 '$:package' => $package_name,
54 '%:attributes' => {},
550d56db 55 '$:attribute_metaclass' => $options{':attribute_metaclass'} || 'Class::MOP::Attribute',
56 '$:method_metaclass' => $options{':method_metaclass'} || 'Class::MOP::Method',
1a7ebbb3 57 } => $class;
58 }
59 else {
5f3c057a 60 # NOTE:
61 # it is safe to use meta here because
62 # class will always be a subclass of
63 # Class::MOP::Class, which defines meta
550d56db 64 $meta = bless $class->meta->construct_instance(%options) => $class
1a7ebbb3 65 }
550d56db 66 # and check the metaclass compatibility
67 $meta->check_metaclass_compatability();
68 $METAS{$package_name} = $meta;
69 }
70
71 sub check_metaclass_compatability {
72 my $self = shift;
73
74 # this is always okay ...
75 return if blessed($self) eq 'Class::MOP::Class';
76
77 my @class_list = $self->class_precedence_list;
78 shift @class_list; # shift off $self->name
79
80 foreach my $class_name (@class_list) {
96ceced8 81 my $meta = $METAS{$class_name} || next;
550d56db 82 ($self->isa(blessed($meta)))
83 || confess $self->name . "->meta => (" . (blessed($self)) . ")" .
84 " is not compatible with the " .
85 $class_name . "->meta => (" . (blessed($meta)) . ")";
86 }
bfe4d0fc 87 }
8b978dd5 88}
89
90sub create {
91 my ($class, $package_name, $package_version, %options) = @_;
bfe4d0fc 92 (defined $package_name && $package_name)
8b978dd5 93 || confess "You must pass a package name";
94 my $code = "package $package_name;";
95 $code .= "\$$package_name\:\:VERSION = '$package_version';"
96 if defined $package_version;
97 eval $code;
98 confess "creation of $package_name failed : $@" if $@;
bfe4d0fc 99 my $meta = $class->initialize($package_name);
aa448b16 100
101 $meta->add_method('meta' => sub {
102 Class::MOP::Class->initialize(blessed($_[0]) || $_[0]);
103 });
104
8b978dd5 105 $meta->superclasses(@{$options{superclasses}})
106 if exists $options{superclasses};
2eb717d5 107 # NOTE:
108 # process attributes first, so that they can
109 # install accessors, but locally defined methods
110 # can then overwrite them. It is maybe a little odd, but
111 # I think this should be the order of things.
112 if (exists $options{attributes}) {
cbd9f942 113 foreach my $attr (@{$options{attributes}}) {
114 $meta->add_attribute($attr);
2eb717d5 115 }
116 }
bfe4d0fc 117 if (exists $options{methods}) {
118 foreach my $method_name (keys %{$options{methods}}) {
119 $meta->add_method($method_name, $options{methods}->{$method_name});
120 }
2eb717d5 121 }
8b978dd5 122 return $meta;
123}
124
7b31baf4 125## Attribute readers
126
127# NOTE:
128# all these attribute readers will be bootstrapped
129# away in the Class::MOP bootstrap section
130
131sub name { $_[0]->{'$:package'} }
132sub get_attribute_map { $_[0]->{'%:attributes'} }
133sub attribute_metaclass { $_[0]->{'$:attribute_metaclass'} }
134sub method_metaclass { $_[0]->{'$:method_metaclass'} }
135
c9e77dbb 136# Instance Construction & Cloning
137
5f3c057a 138sub new_object {
139 my $class = shift;
651955fb 140 # NOTE:
141 # we need to protect the integrity of the
142 # Class::MOP::Class singletons here, so we
143 # delegate this to &construct_class_instance
144 # which will deal with the singletons
145 return $class->construct_class_instance(@_)
146 if $class->name->isa('Class::MOP::Class');
5f3c057a 147 bless $class->construct_instance(@_) => $class->name;
148}
e16da3e6 149
150sub construct_instance {
cbd9f942 151 my ($class, %params) = @_;
152 my $instance = {};
c9e77dbb 153 foreach my $attr ($class->compute_all_applicable_attributes()) {
651955fb 154 my $init_arg = $attr->init_arg();
cbd9f942 155 # try to fetch the init arg from the %params ...
156 my $val;
157 $val = $params{$init_arg} if exists $params{$init_arg};
158 # if nothing was in the %params, we can use the
159 # attribute's default value (if it has one)
c9e77dbb 160 $val ||= $attr->default($instance) if $attr->has_default();
cbd9f942 161 $instance->{$attr->name} = $val;
162 }
163 return $instance;
e16da3e6 164}
165
5f3c057a 166sub clone_object {
167 my $class = shift;
7b31baf4 168 my $instance = shift;
651955fb 169 (blessed($instance) && $instance->isa($class->name))
170 || confess "You must pass an instance ($instance) of the metaclass (" . $class->name . ")";
171 # NOTE:
172 # we need to protect the integrity of the
173 # Class::MOP::Class singletons here, they
a740253a 174 # should not be cloned.
651955fb 175 return $instance if $instance->isa('Class::MOP::Class');
176 bless $class->clone_instance($instance, @_) => blessed($instance);
5f3c057a 177}
178
c9e77dbb 179sub clone_instance {
651955fb 180 my ($class, $instance, %params) = @_;
181 (blessed($instance))
c9e77dbb 182 || confess "You can only clone instances, \$self is not a blessed instance";
19d4b5b8 183 my $clone = { %$instance, %params };
c9e77dbb 184 return $clone;
185}
186
8b978dd5 187# Informational
188
7b31baf4 189# &name should be here too, but it is above
190# because it gets bootstrapped away
8b978dd5 191
192sub version {
193 my $self = shift;
96ceced8 194 ${$self->get_package_variable('$VERSION')};
8b978dd5 195}
196
197# Inheritance
198
199sub superclasses {
200 my $self = shift;
8b978dd5 201 if (@_) {
202 my @supers = @_;
96ceced8 203 @{$self->get_package_variable('@ISA')} = @supers;
8b978dd5 204 }
96ceced8 205 @{$self->get_package_variable('@ISA')};
8b978dd5 206}
207
208sub class_precedence_list {
209 my $self = shift;
bfe4d0fc 210 # NOTE:
211 # We need to check for ciruclar inheirtance here.
212 # This will do nothing if all is well, and blow
213 # up otherwise. Yes, it's an ugly hack, better
214 # suggestions are welcome.
215 { $self->name->isa('This is a test for circular inheritance') }
216 # ... and no back to our regularly scheduled program
8b978dd5 217 (
218 $self->name,
219 map {
bfe4d0fc 220 $self->initialize($_)->class_precedence_list()
8b978dd5 221 } $self->superclasses()
222 );
223}
224
0882828e 225## Methods
226
227sub add_method {
228 my ($self, $method_name, $method) = @_;
229 (defined $method_name && $method_name)
230 || confess "You must define a method name";
a5eca695 231 # use reftype here to allow for blessed subs ...
ee5e71d4 232 ('CODE' eq (reftype($method) || ''))
0882828e 233 || confess "Your code block must be a CODE reference";
234 my $full_method_name = ($self->name . '::' . $method_name);
de19f115 235
a4258ffd 236 $method = $self->method_metaclass->wrap($method) unless blessed($method);
de19f115 237
0882828e 238 no strict 'refs';
c9b8b7f9 239 no warnings 'redefine';
22286063 240 *{$full_method_name} = subname $full_method_name => $method;
0882828e 241}
242
a4258ffd 243{
244 my $fetch_and_prepare_method = sub {
245 my ($self, $method_name) = @_;
246 # fetch it locally
247 my $method = $self->get_method($method_name);
248 # if we dont have local ...
249 unless ($method) {
96ceced8 250 # make sure this method even exists ...
251 ($self->find_next_method_by_name($method_name))
252 || confess "The method '$method_name' is not found in the inherience hierarchy for this class";
253 # if so, then create a local which just
254 # calls the next applicable method ...
255 $self->add_method($method_name => sub {
256 $self->find_next_method_by_name($method_name)->(@_);
257 });
a4258ffd 258 $method = $self->get_method($method_name);
259 }
260
261 # now make sure we wrap it properly
262 # (if it isnt already)
263 unless ($method->isa('Class::MOP::Method::Wrapped')) {
264 $method = Class::MOP::Method::Wrapped->wrap($method);
265 $self->add_method($method_name => $method);
266 }
267 return $method;
268 };
269
270 sub add_before_method_modifier {
271 my ($self, $method_name, $method_modifier) = @_;
272 (defined $method_name && $method_name)
273 || confess "You must pass in a method name";
274 my $full_method_modifier_name = ($self->name . '::' . $method_name . ':before');
275 my $method = $fetch_and_prepare_method->($self, $method_name);
276 $method->add_before_modifier(subname $full_method_modifier_name => $method_modifier);
277 }
ddc8edba 278
a4258ffd 279 sub add_after_method_modifier {
280 my ($self, $method_name, $method_modifier) = @_;
281 (defined $method_name && $method_name)
282 || confess "You must pass in a method name";
283 my $full_method_modifier_name = ($self->name . '::' . $method_name . ':after');
284 my $method = $fetch_and_prepare_method->($self, $method_name);
285 $method->add_after_modifier(subname $full_method_modifier_name => $method_modifier);
ddc8edba 286 }
287
a4258ffd 288 sub add_around_method_modifier {
289 my ($self, $method_name, $method_modifier) = @_;
290 (defined $method_name && $method_name)
291 || confess "You must pass in a method name";
292 my $full_method_modifier_name = ($self->name . '::' . $method_name . ':around');
293 my $method = $fetch_and_prepare_method->($self, $method_name);
294 $method->add_around_modifier(subname $full_method_modifier_name => $method_modifier);
295 }
296
ee5e71d4 297}
298
663f8198 299sub alias_method {
300 my ($self, $method_name, $method) = @_;
301 (defined $method_name && $method_name)
302 || confess "You must define a method name";
303 # use reftype here to allow for blessed subs ...
ee5e71d4 304 ('CODE' eq (reftype($method) || ''))
663f8198 305 || confess "Your code block must be a CODE reference";
de19f115 306 my $full_method_name = ($self->name . '::' . $method_name);
307
a4258ffd 308 $method = $self->method_metaclass->wrap($method) unless blessed($method);
663f8198 309
310 no strict 'refs';
311 no warnings 'redefine';
312 *{$full_method_name} = $method;
313}
314
de19f115 315sub has_method {
316 my ($self, $method_name) = @_;
317 (defined $method_name && $method_name)
318 || confess "You must define a method name";
bfe4d0fc 319
de19f115 320 my $sub_name = ($self->name . '::' . $method_name);
0882828e 321
de19f115 322 no strict 'refs';
323 return 0 if !defined(&{$sub_name});
de19f115 324 my $method = \&{$sub_name};
96ceced8 325 return 0 if (svref_2object($method)->GV->STASH->NAME || '') ne $self->name &&
326 (svref_2object($method)->GV->NAME || '') ne '__ANON__';
de19f115 327
96ceced8 328 # at this point we are relatively sure
329 # it is our method, so we bless/wrap it
330 $self->method_metaclass->wrap($method) unless blessed($method);
de19f115 331 return 1;
0882828e 332}
333
334sub get_method {
c9b8b7f9 335 my ($self, $method_name) = @_;
0882828e 336 (defined $method_name && $method_name)
337 || confess "You must define a method name";
338
de19f115 339 return unless $self->has_method($method_name);
340
0882828e 341 no strict 'refs';
de19f115 342 return \&{$self->name . '::' . $method_name};
c9b8b7f9 343}
344
345sub remove_method {
346 my ($self, $method_name) = @_;
347 (defined $method_name && $method_name)
348 || confess "You must define a method name";
349
350 my $removed_method = $self->get_method($method_name);
351
352 no strict 'refs';
353 delete ${$self->name . '::'}{$method_name}
354 if defined $removed_method;
355
356 return $removed_method;
357}
358
359sub get_method_list {
360 my $self = shift;
361 no strict 'refs';
a5eca695 362 grep { $self->has_method($_) } %{$self->name . '::'};
363}
364
365sub compute_all_applicable_methods {
366 my $self = shift;
367 my @methods;
368 # keep a record of what we have seen
369 # here, this will handle all the
370 # inheritence issues because we are
371 # using the &class_precedence_list
372 my (%seen_class, %seen_method);
373 foreach my $class ($self->class_precedence_list()) {
374 next if $seen_class{$class};
375 $seen_class{$class}++;
376 # fetch the meta-class ...
377 my $meta = $self->initialize($class);
378 foreach my $method_name ($meta->get_method_list()) {
379 next if exists $seen_method{$method_name};
380 $seen_method{$method_name}++;
381 push @methods => {
382 name => $method_name,
383 class => $class,
384 code => $meta->get_method($method_name)
385 };
386 }
387 }
388 return @methods;
389}
390
a5eca695 391sub find_all_methods_by_name {
392 my ($self, $method_name) = @_;
393 (defined $method_name && $method_name)
394 || confess "You must define a method name to find";
395 my @methods;
396 # keep a record of what we have seen
397 # here, this will handle all the
398 # inheritence issues because we are
399 # using the &class_precedence_list
400 my %seen_class;
401 foreach my $class ($self->class_precedence_list()) {
402 next if $seen_class{$class};
403 $seen_class{$class}++;
404 # fetch the meta-class ...
96ceced8 405 my $meta = $self->initialize($class);
a5eca695 406 push @methods => {
407 name => $method_name,
408 class => $class,
409 code => $meta->get_method($method_name)
410 } if $meta->has_method($method_name);
411 }
412 return @methods;
8b978dd5 413}
414
96ceced8 415sub find_next_method_by_name {
416 my ($self, $method_name) = @_;
417 (defined $method_name && $method_name)
418 || confess "You must define a method name to find";
419 # keep a record of what we have seen
420 # here, this will handle all the
421 # inheritence issues because we are
422 # using the &class_precedence_list
423 my %seen_class;
424 my @cpl = $self->class_precedence_list();
425 shift @cpl; # discard ourselves
426 foreach my $class (@cpl) {
427 next if $seen_class{$class};
428 $seen_class{$class}++;
429 # fetch the meta-class ...
430 my $meta = $self->initialize($class);
431 return $meta->get_method($method_name)
432 if $meta->has_method($method_name);
433 }
434 return;
435}
436
552e3d24 437## Attributes
438
e16da3e6 439sub add_attribute {
2e41896e 440 my $self = shift;
441 # either we have an attribute object already
442 # or we need to create one from the args provided
443 my $attribute = blessed($_[0]) ? $_[0] : $self->attribute_metaclass->new(@_);
444 # make sure it is derived from the correct type though
445 ($attribute->isa('Class::MOP::Attribute'))
446 || confess "Your attribute must be an instance of Class::MOP::Attribute (or a subclass)";
9ec169fe 447 $attribute->attach_to_class($self);
448 $attribute->install_accessors();
7b31baf4 449 $self->get_attribute_map->{$attribute->name} = $attribute;
e16da3e6 450}
451
452sub has_attribute {
453 my ($self, $attribute_name) = @_;
454 (defined $attribute_name && $attribute_name)
455 || confess "You must define an attribute name";
7b31baf4 456 exists $self->get_attribute_map->{$attribute_name} ? 1 : 0;
e16da3e6 457}
458
459sub get_attribute {
460 my ($self, $attribute_name) = @_;
461 (defined $attribute_name && $attribute_name)
462 || confess "You must define an attribute name";
7b31baf4 463 return $self->get_attribute_map->{$attribute_name}
22286063 464 if $self->has_attribute($attribute_name);
465 return;
e16da3e6 466}
467
468sub remove_attribute {
469 my ($self, $attribute_name) = @_;
470 (defined $attribute_name && $attribute_name)
471 || confess "You must define an attribute name";
7b31baf4 472 my $removed_attribute = $self->get_attribute_map->{$attribute_name};
22286063 473 return unless defined $removed_attribute;
474 delete $self->get_attribute_map->{$attribute_name};
9ec169fe 475 $removed_attribute->remove_accessors();
476 $removed_attribute->detach_from_class();
e16da3e6 477 return $removed_attribute;
478}
479
480sub get_attribute_list {
481 my $self = shift;
7b31baf4 482 keys %{$self->get_attribute_map};
e16da3e6 483}
484
485sub compute_all_applicable_attributes {
486 my $self = shift;
487 my @attrs;
488 # keep a record of what we have seen
489 # here, this will handle all the
490 # inheritence issues because we are
491 # using the &class_precedence_list
492 my (%seen_class, %seen_attr);
493 foreach my $class ($self->class_precedence_list()) {
494 next if $seen_class{$class};
495 $seen_class{$class}++;
496 # fetch the meta-class ...
497 my $meta = $self->initialize($class);
498 foreach my $attr_name ($meta->get_attribute_list()) {
499 next if exists $seen_attr{$attr_name};
500 $seen_attr{$attr_name}++;
c9e77dbb 501 push @attrs => $meta->get_attribute($attr_name);
e16da3e6 502 }
503 }
504 return @attrs;
505}
2eb717d5 506
52e8a34c 507# Class attributes
508
509sub add_package_variable {
510 my ($self, $variable, $initial_value) = @_;
511 (defined $variable && $variable =~ /^[\$\@\%]/)
512 || confess "variable name does not have a sigil";
513
514 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
515 if (defined $initial_value) {
516 no strict 'refs';
517 *{$self->name . '::' . $name} = $initial_value;
518 }
519 else {
520 eval $sigil . $self->name . '::' . $name;
521 confess "Could not create package variable ($variable) because : $@" if $@;
522 }
523}
524
525sub has_package_variable {
526 my ($self, $variable) = @_;
527 (defined $variable && $variable =~ /^[\$\@\%]/)
528 || confess "variable name does not have a sigil";
529 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
530 no strict 'refs';
531 defined ${$self->name . '::'}{$name} ? 1 : 0;
532}
533
534sub get_package_variable {
535 my ($self, $variable) = @_;
536 (defined $variable && $variable =~ /^[\$\@\%]/)
537 || confess "variable name does not have a sigil";
538 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
539 no strict 'refs';
540 # try to fetch it first,.. see what happens
18697ac8 541 my $ref = eval '\\' . $sigil . $self->name . '::' . $name;
52e8a34c 542 confess "Could not get the package variable ($variable) because : $@" if $@;
543 # if we didn't die, then we can return it
18697ac8 544 return $ref;
52e8a34c 545}
546
547sub remove_package_variable {
548 my ($self, $variable) = @_;
549 (defined $variable && $variable =~ /^[\$\@\%]/)
550 || confess "variable name does not have a sigil";
551 my ($sigil, $name) = ($variable =~ /^(.)(.*)$/);
552 no strict 'refs';
553 delete ${$self->name . '::'}{$name};
554}
555
8b978dd5 5561;
557
558__END__
559
560=pod
561
562=head1 NAME
563
564Class::MOP::Class - Class Meta Object
565
566=head1 SYNOPSIS
567
fe122940 568 # use this for introspection ...
569
fe122940 570 # add a method to Foo ...
571 Foo->meta->add_method('bar' => sub { ... })
572
573 # get a list of all the classes searched
574 # the method dispatcher in the correct order
575 Foo->meta->class_precedence_list()
576
577 # remove a method from Foo
578 Foo->meta->remove_method('bar');
579
580 # or use this to actually create classes ...
581
582 Class::MOP::Class->create('Bar' => '0.01' => (
583 superclasses => [ 'Foo' ],
584 attributes => [
585 Class::MOP:::Attribute->new('$bar'),
586 Class::MOP:::Attribute->new('$baz'),
587 ],
588 methods => {
589 calculate_bar => sub { ... },
590 construct_baz => sub { ... }
591 }
592 ));
593
8b978dd5 594=head1 DESCRIPTION
595
fe122940 596This is the largest and currently most complex part of the Perl 5
597meta-object protocol. It controls the introspection and
598manipulation of Perl 5 classes (and it can create them too). The
599best way to understand what this module can do, is to read the
600documentation for each of it's methods.
601
552e3d24 602=head1 METHODS
603
2eb717d5 604=head2 Self Introspection
605
606=over 4
607
608=item B<meta>
609
fe122940 610This will return a B<Class::MOP::Class> instance which is related
611to this class. Thereby allowing B<Class::MOP::Class> to actually
612introspect itself.
613
614As with B<Class::MOP::Attribute>, B<Class::MOP> will actually
615bootstrap this module by installing a number of attribute meta-objects
616into it's metaclass. This will allow this class to reap all the benifits
617of the MOP when subclassing it.
2eb717d5 618
619=back
620
552e3d24 621=head2 Class construction
622
a2e85e6c 623These methods will handle creating B<Class::MOP::Class> objects,
624which can be used to both create new classes, and analyze
625pre-existing classes.
552e3d24 626
627This module will internally store references to all the instances
628you create with these methods, so that they do not need to be
629created any more than nessecary. Basically, they are singletons.
630
631=over 4
632
633=item B<create ($package_name, ?$package_version,
a2e85e6c 634 superclasses =E<gt> ?@superclasses,
635 methods =E<gt> ?%methods,
636 attributes =E<gt> ?%attributes)>
552e3d24 637
a2e85e6c 638This returns a B<Class::MOP::Class> object, bringing the specified
552e3d24 639C<$package_name> into existence and adding any of the
640C<$package_version>, C<@superclasses>, C<%methods> and C<%attributes>
641to it.
642
643=item B<initialize ($package_name)>
644
a2e85e6c 645This initializes and returns returns a B<Class::MOP::Class> object
646for a given a C<$package_name>.
647
651955fb 648=item B<construct_class_instance (%options)>
a2e85e6c 649
650This will construct an instance of B<Class::MOP::Class>, it is
651here so that we can actually "tie the knot" for B<Class::MOP::Class>
652to use C<construct_instance> once all the bootstrapping is done. This
653method is used internally by C<initialize> and should never be called
654from outside of that method really.
552e3d24 655
550d56db 656=item B<check_metaclass_compatability>
657
658This method is called as the very last thing in the
659C<construct_class_instance> method. This will check that the
660metaclass you are creating is compatible with the metaclasses of all
661your ancestors. For more inforamtion about metaclass compatibility
662see the C<About Metaclass compatibility> section in L<Class::MOP>.
663
552e3d24 664=back
665
c9e77dbb 666=head2 Object instance construction and cloning
a2e85e6c 667
c9e77dbb 668These methods are B<entirely optional>, it is up to you whether you want
669to use them or not.
552e3d24 670
671=over 4
672
5f3c057a 673=item B<new_object (%params)>
674
675This is a convience method for creating a new object of the class, and
676blessing it into the appropriate package as well. Ideally your class
677would call a C<new> this method like so:
678
679 sub MyClass::new {
680 my ($class, %param) = @_;
681 $class->meta->new_object(%params);
682 }
683
684Of course the ideal place for this would actually be in C<UNIVERSAL::>
685but that is considered bad style, so we do not do that.
686
cbd9f942 687=item B<construct_instance (%params)>
552e3d24 688
c9e77dbb 689This method is used to construct an instace structure suitable for
690C<bless>-ing into your package of choice. It works in conjunction
691with the Attribute protocol to collect all applicable attributes.
692
cbd9f942 693This will construct and instance using a HASH ref as storage
552e3d24 694(currently only HASH references are supported). This will collect all
a2e85e6c 695the applicable attributes and layout out the fields in the HASH ref,
696it will then initialize them using either use the corresponding key
697in C<%params> or any default value or initializer found in the
698attribute meta-object.
727919c5 699
5f3c057a 700=item B<clone_object ($instance, %params)>
701
702This is a convience method for cloning an object instance, then
19d4b5b8 703blessing it into the appropriate package. This method will call
704C<clone_instance>, which performs a shallow copy of the object,
705see that methods documentation for more details. Ideally your
706class would call a C<clone> this method like so:
5f3c057a 707
708 sub MyClass::clone {
709 my ($self, %param) = @_;
710 $self->meta->clone_object($self, %params);
711 }
712
713Of course the ideal place for this would actually be in C<UNIVERSAL::>
714but that is considered bad style, so we do not do that.
715
c9e77dbb 716=item B<clone_instance($instance, %params)>
717
718This method is a compliment of C<construct_instance> (which means if
19d4b5b8 719you override C<construct_instance>, you need to override this one too),
720and clones the instance shallowly.
a27ae83f 721
722The cloned structure returned is (like with C<construct_instance>) an
723unC<bless>ed HASH reference, it is your responsibility to then bless
724this cloned structure into the right class (which C<clone_object> will
725do for you).
c9e77dbb 726
19d4b5b8 727As of 0.11, this method will clone the C<$instance> structure shallowly,
728as opposed to the deep cloning implemented in prior versions. After much
729thought, research and discussion, I have decided that anything but basic
730shallow cloning is outside the scope of the meta-object protocol. I
731think Yuval "nothingmuch" Kogman put it best when he said that cloning
732is too I<context-specific> to be part of the MOP.
733
552e3d24 734=back
735
736=head2 Informational
737
738=over 4
739
740=item B<name>
741
a2e85e6c 742This is a read-only attribute which returns the package name for the
743given B<Class::MOP::Class> instance.
552e3d24 744
745=item B<version>
746
747This is a read-only attribute which returns the C<$VERSION> of the
a2e85e6c 748package for the given B<Class::MOP::Class> instance.
552e3d24 749
750=back
751
752=head2 Inheritance Relationships
753
754=over 4
755
756=item B<superclasses (?@superclasses)>
757
758This is a read-write attribute which represents the superclass
a2e85e6c 759relationships of the class the B<Class::MOP::Class> instance is
760associated with. Basically, it can get and set the C<@ISA> for you.
552e3d24 761
343203ee 762B<NOTE:>
763Perl will occasionally perform some C<@ISA> and method caching, if
764you decide to change your superclass relationship at runtime (which
765is quite insane and very much not recommened), then you should be
766aware of this and the fact that this module does not make any
767attempt to address this issue.
768
552e3d24 769=item B<class_precedence_list>
770
a2e85e6c 771This computes the a list of all the class's ancestors in the same order
772in which method dispatch will be done. This is similair to
773what B<Class::ISA::super_path> does, but we don't remove duplicate names.
552e3d24 774
775=back
776
777=head2 Methods
778
779=over 4
780
2e41896e 781=item B<method_metaclass>
782
552e3d24 783=item B<add_method ($method_name, $method)>
784
785This will take a C<$method_name> and CODE reference to that
a2e85e6c 786C<$method> and install it into the class's package.
552e3d24 787
a2e85e6c 788B<NOTE>:
789This does absolutely nothing special to C<$method>
552e3d24 790other than use B<Sub::Name> to make sure it is tagged with the
791correct name, and therefore show up correctly in stack traces and
792such.
793
663f8198 794=item B<alias_method ($method_name, $method)>
795
796This will take a C<$method_name> and CODE reference to that
797C<$method> and alias the method into the class's package.
798
799B<NOTE>:
800Unlike C<add_method>, this will B<not> try to name the
801C<$method> using B<Sub::Name>, it only aliases the method in
802the class's package.
803
552e3d24 804=item B<has_method ($method_name)>
805
a2e85e6c 806This just provides a simple way to check if the class implements
552e3d24 807a specific C<$method_name>. It will I<not> however, attempt to check
a2e85e6c 808if the class inherits the method (use C<UNIVERSAL::can> for that).
552e3d24 809
810This will correctly handle functions defined outside of the package
811that use a fully qualified name (C<sub Package::name { ... }>).
812
813This will correctly handle functions renamed with B<Sub::Name> and
814installed using the symbol tables. However, if you are naming the
815subroutine outside of the package scope, you must use the fully
816qualified name, including the package name, for C<has_method> to
817correctly identify it.
818
819This will attempt to correctly ignore functions imported from other
820packages using B<Exporter>. It breaks down if the function imported
821is an C<__ANON__> sub (such as with C<use constant>), which very well
822may be a valid method being applied to the class.
823
824In short, this method cannot always be trusted to determine if the
825C<$method_name> is actually a method. However, it will DWIM about
a2e85e6c 82690% of the time, so it's a small trade off I think.
552e3d24 827
828=item B<get_method ($method_name)>
829
830This will return a CODE reference of the specified C<$method_name>,
831or return undef if that method does not exist.
832
833=item B<remove_method ($method_name)>
834
a2e85e6c 835This will attempt to remove a given C<$method_name> from the class.
552e3d24 836It will return the CODE reference that it has removed, and will
837attempt to use B<Sub::Name> to clear the methods associated name.
838
839=item B<get_method_list>
840
841This will return a list of method names for all I<locally> defined
842methods. It does B<not> provide a list of all applicable methods,
843including any inherited ones. If you want a list of all applicable
844methods, use the C<compute_all_applicable_methods> method.
845
846=item B<compute_all_applicable_methods>
847
a2e85e6c 848This will return a list of all the methods names this class will
849respond to, taking into account inheritance. The list will be a list of
552e3d24 850HASH references, each one containing the following information; method
851name, the name of the class in which the method lives and a CODE
852reference for the actual method.
853
854=item B<find_all_methods_by_name ($method_name)>
855
856This will traverse the inheritence hierarchy and locate all methods
857with a given C<$method_name>. Similar to
858C<compute_all_applicable_methods> it returns a list of HASH references
859with the following information; method name (which will always be the
860same as C<$method_name>), the name of the class in which the method
861lives and a CODE reference for the actual method.
862
863The list of methods produced is a distinct list, meaning there are no
864duplicates in it. This is especially useful for things like object
865initialization and destruction where you only want the method called
866once, and in the correct order.
867
96ceced8 868=item B<find_next_method_by_name ($method_name)>
869
870This will return the first method to match a given C<$method_name> in
871the superclasses, this is basically equivalent to calling
872C<SUPER::$method_name>, but it can be dispatched at runtime.
873
552e3d24 874=back
875
a4258ffd 876=head2 Method Modifiers
877
96ceced8 878Method modifiers are a concept borrowed from CLOS, in which a method
879can be wrapped with I<before>, I<after> and I<around> method modifiers
880that will be called everytime the method is called.
881
882=head3 How method modifiers work?
883
884Method modifiers work by wrapping the original method and then replacing
885it in the classes symbol table. The wrappers will handle calling all the
886modifiers in the appropariate orders and preserving the calling context
887for the original method.
888
889Each method modifier serves a particular purpose, which may not be
890obvious to users of other method wrapping modules. To start with, the
891return values of I<before> and I<after> modifiers are ignored. This is
892because thier purpose is B<not> to filter the input and output of the
893primary method (this is done with an I<around> modifier). This may seem
894like an odd restriction to some, but doing this allows for simple code
895to be added at the begining or end of a method call without jeapordizing
896the normal functioning of the primary method or placing any extra
897responsibility on the code of the modifier. Of course if you have more
898complex needs, then use the I<around> modifier, which uses a variation
899of continutation passing style to allow for a high degree of flexibility.
900
901Before and around modifiers are called in last-defined-first-called order,
902while after modifiers are called in first-defined-first-called order. So
903the call tree might looks something like this:
904
905 before 2
906 before 1
907 around 2
908 around 1
909 primary
910 after 1
911 after 2
912
913To see examples of using method modifiers, see the following examples
914included in the distribution; F<InstanceCountingClass>, F<Perl6Attribute>,
915F<AttributesWithHistory> and F<C3MethodDispatchOrder>. There is also a
916classic CLOS usage example in the test F<017_add_method_modifier.t>.
917
918=head3 What is the performance impact?
919
920Of course there is a performance cost associated with method modifiers,
921but we have made every effort to make that cost be directly proportional
922to the amount of modifier features you utilize.
923
924The wrapping method does it's best to B<only> do as much work as it
925absolutely needs to. In order to do this we have moved some of the
926performance costs to set-up time, where they are easier to amortize.
927
928All this said, my benchmarks have indicated the following:
929
930 simple wrapper with no modifiers 100% slower
931 simple wrapper with simple before modifier 400% slower
932 simple wrapper with simple after modifier 450% slower
933 simple wrapper with simple around modifier 500-550% slower
934 simple wrapper with all 3 modifiers 1100% slower
935
936These numbers may seem daunting, but you must remember, every feature
937comes with some cost. To put things in perspective, just doing a simple
938C<AUTOLOAD> which does nothing but extract the name of the method called
939and return it costs about 400% over a normal method call.
940
a4258ffd 941=over 4
942
943=item B<add_before_method_modifier ($method_name, $code)>
944
96ceced8 945This will wrap the method at C<$method_name> and the supplied C<$code>
946will be passed the C<@_> arguments, and called before the original
947method is called. As specified above, the return value of the I<before>
948method modifiers is ignored, and it's ability to modify C<@_> is
949fairly limited. If you need to do either of these things, use an
950C<around> method modifier.
951
a4258ffd 952=item B<add_after_method_modifier ($method_name, $code)>
953
96ceced8 954This will wrap the method at C<$method_name> so that the original
955method will be called, it's return values stashed, and then the
956supplied C<$code> will be passed the C<@_> arguments, and called.
957As specified above, the return value of the I<after> method
958modifiers is ignored, and it cannot modify the return values of
959the original method. If you need to do either of these things, use an
960C<around> method modifier.
961
a4258ffd 962=item B<add_around_method_modifier ($method_name, $code)>
963
96ceced8 964This will wrap the method at C<$method_name> so that C<$code>
965will be called and passed the original method as an extra argument
966at the begining of the C<@_> argument list. This is a variation of
967continuation passing style, where the function prepended to C<@_>
968can be considered a continuation. It is up to C<$code> if it calls
969the original method or not, there is no restriction on what the
970C<$code> can or cannot do.
971
a4258ffd 972=back
973
552e3d24 974=head2 Attributes
975
976It should be noted that since there is no one consistent way to define
977the attributes of a class in Perl 5. These methods can only work with
978the information given, and can not easily discover information on
a2e85e6c 979their own. See L<Class::MOP::Attribute> for more details.
552e3d24 980
981=over 4
982
2e41896e 983=item B<attribute_metaclass>
984
7b31baf4 985=item B<get_attribute_map>
986
552e3d24 987=item B<add_attribute ($attribute_name, $attribute_meta_object)>
988
a2e85e6c 989This stores a C<$attribute_meta_object> in the B<Class::MOP::Class>
990instance associated with the given class, and associates it with
991the C<$attribute_name>. Unlike methods, attributes within the MOP
992are stored as meta-information only. They will be used later to
993construct instances from (see C<construct_instance> above).
552e3d24 994More details about the attribute meta-objects can be found in the
a2e85e6c 995L<Class::MOP::Attribute> or the L<Class::MOP/The Attribute protocol>
996section.
997
998It should be noted that any accessor, reader/writer or predicate
999methods which the C<$attribute_meta_object> has will be installed
1000into the class at this time.
552e3d24 1001
1002=item B<has_attribute ($attribute_name)>
1003
a2e85e6c 1004Checks to see if this class has an attribute by the name of
552e3d24 1005C<$attribute_name> and returns a boolean.
1006
1007=item B<get_attribute ($attribute_name)>
1008
1009Returns the attribute meta-object associated with C<$attribute_name>,
1010if none is found, it will return undef.
1011
1012=item B<remove_attribute ($attribute_name)>
1013
1014This will remove the attribute meta-object stored at
1015C<$attribute_name>, then return the removed attribute meta-object.
1016
a2e85e6c 1017B<NOTE:>
1018Removing an attribute will only affect future instances of
552e3d24 1019the class, it will not make any attempt to remove the attribute from
1020any existing instances of the class.
1021
a2e85e6c 1022It should be noted that any accessor, reader/writer or predicate
1023methods which the attribute meta-object stored at C<$attribute_name>
1024has will be removed from the class at this time. This B<will> make
1025these attributes somewhat inaccessable in previously created
1026instances. But if you are crazy enough to do this at runtime, then
1027you are crazy enough to deal with something like this :).
1028
552e3d24 1029=item B<get_attribute_list>
1030
1031This returns a list of attribute names which are defined in the local
1032class. If you want a list of all applicable attributes for a class,
1033use the C<compute_all_applicable_attributes> method.
1034
1035=item B<compute_all_applicable_attributes>
1036
c9e77dbb 1037This will traverse the inheritance heirachy and return a list of all
1038the applicable attributes for this class. It does not construct a
1039HASH reference like C<compute_all_applicable_methods> because all
1040that same information is discoverable through the attribute
1041meta-object itself.
552e3d24 1042
1043=back
1044
52e8a34c 1045=head2 Package Variables
1046
1047Since Perl's classes are built atop the Perl package system, it is
1048fairly common to use package scoped variables for things like static
1049class variables. The following methods are convience methods for
1050the creation and inspection of package scoped variables.
1051
1052=over 4
1053
1054=item B<add_package_variable ($variable_name, ?$initial_value)>
1055
1056Given a C<$variable_name>, which must contain a leading sigil, this
1057method will create that variable within the package which houses the
1058class. It also takes an optional C<$initial_value>, which must be a
1059reference of the same type as the sigil of the C<$variable_name>
1060implies.
1061
1062=item B<get_package_variable ($variable_name)>
1063
1064This will return a reference to the package variable in
1065C<$variable_name>.
1066
1067=item B<has_package_variable ($variable_name)>
1068
1069Returns true (C<1>) if there is a package variable defined for
1070C<$variable_name>, and false (C<0>) otherwise.
1071
1072=item B<remove_package_variable ($variable_name)>
1073
1074This will attempt to remove the package variable at C<$variable_name>.
1075
1076=back
1077
8b978dd5 1078=head1 AUTHOR
1079
a2e85e6c 1080Stevan Little E<lt>stevan@iinteractive.comE<gt>
8b978dd5 1081
1082=head1 COPYRIGHT AND LICENSE
1083
1084Copyright 2006 by Infinity Interactive, Inc.
1085
1086L<http://www.iinteractive.com>
1087
1088This library is free software; you can redistribute it and/or modify
1089it under the same terms as Perl itself.
1090
1091=cut