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