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