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