copyright date changes on Class::MOP
[gitmo/Class-MOP.git] / lib / Class / MOP / Attribute.pm
1
2 package Class::MOP::Attribute;
3
4 use strict;
5 use warnings;
6
7 use Class::MOP::Method::Accessor;
8
9 use Carp         'confess';
10 use Scalar::Util 'blessed', 'reftype', 'weaken';
11
12 our $VERSION   = '0.22';
13 our $AUTHORITY = 'cpan:STEVAN';
14
15 use base 'Class::MOP::Object';
16
17 sub meta {
18     require Class::MOP::Class;
19     Class::MOP::Class->initialize(blessed($_[0]) || $_[0]);
20 }
21
22 # NOTE: (meta-circularity)
23 # This method will be replaced in the
24 # boostrap section of Class::MOP, by
25 # a new version which uses the
26 # &Class::MOP::Class::construct_instance
27 # method to build an attribute meta-object
28 # which itself is described with attribute
29 # meta-objects.
30 #     - Ain't meta-circularity grand? :)
31 sub new {
32     my $class   = shift;
33     my $name    = shift;
34     my %options = @_;
35
36     (defined $name && $name)
37         || confess "You must provide a name for the attribute";
38
39     $options{init_arg} = $name
40         if not exists $options{init_arg};
41     if(exists $options{builder}){
42         confess("builder must be a defined scalar value which is a method name")
43             if ref $options{builder} || !(defined $options{builder});
44         confess("Setting both default and builder is not allowed.")
45             if exists $options{default};
46     } else {
47         (is_default_a_coderef(\%options))
48             || confess("References are not allowed as default values, you must ".
49                        "wrap then in a CODE reference (ex: sub { [] } and not [])")
50                 if exists $options{default} && ref $options{default};
51     }
52     bless {
53         '$!name'      => $name,
54         '$!accessor'  => $options{accessor},
55         '$!reader'    => $options{reader},
56         '$!writer'    => $options{writer},
57         '$!predicate' => $options{predicate},
58         '$!clearer'   => $options{clearer},
59         '$!builder'   => $options{builder},
60         '$!init_arg'  => $options{init_arg},
61         '$!default'   => $options{default},
62         # keep a weakened link to the
63         # class we are associated with
64         '$!associated_class' => undef,
65         # and a list of the methods
66         # associated with this attr
67         '@!associated_methods' => [],
68     } => $class;
69 }
70
71 # NOTE:
72 # this is a primative (and kludgy) clone operation
73 # for now, it will be replaced in the Class::MOP
74 # bootstrap with a proper one, however we know
75 # that this one will work fine for now.
76 sub clone {
77     my $self    = shift;
78     my %options = @_;
79     (blessed($self))
80         || confess "Can only clone an instance";
81     return bless { %{$self}, %options } => blessed($self);
82 }
83
84 sub initialize_instance_slot {
85     my ($self, $meta_instance, $instance, $params) = @_;
86     my $init_arg = $self->{'$!init_arg'};
87     # try to fetch the init arg from the %params ...
88
89     # if nothing was in the %params, we can use the
90     # attribute's default value (if it has one)
91     if(exists $params->{$init_arg}){
92         $meta_instance->set_slot_value($instance, $self->name, $params->{$init_arg});
93     } 
94     elsif (defined $self->{'$!default'}) {
95         $meta_instance->set_slot_value($instance, $self->name, $self->default($instance));
96     } 
97     elsif (defined( my $builder = $self->{'$!builder'})) {
98         if ($builder = $instance->can($builder)) {
99             $meta_instance->set_slot_value($instance, $self->name, $instance->$builder);
100         } 
101         else {
102             confess(blessed($instance)." does not support builder method '". $self->{'$!builder'} ."' for attribute '" . $self->name . "'");
103         }
104     }
105 }
106
107 # NOTE:
108 # the next bunch of methods will get bootstrapped
109 # away in the Class::MOP bootstrapping section
110
111 sub name { $_[0]->{'$!name'} }
112
113 sub associated_class   { $_[0]->{'$!associated_class'}   }
114 sub associated_methods { $_[0]->{'@!associated_methods'} }
115
116 sub has_accessor  { defined($_[0]->{'$!accessor'})  ? 1 : 0 }
117 sub has_reader    { defined($_[0]->{'$!reader'})    ? 1 : 0 }
118 sub has_writer    { defined($_[0]->{'$!writer'})    ? 1 : 0 }
119 sub has_predicate { defined($_[0]->{'$!predicate'}) ? 1 : 0 }
120 sub has_clearer   { defined($_[0]->{'$!clearer'})   ? 1 : 0 }
121 sub has_builder   { defined($_[0]->{'$!builder'})   ? 1 : 0 }
122 sub has_init_arg  { defined($_[0]->{'$!init_arg'})  ? 1 : 0 }
123 sub has_default   { defined($_[0]->{'$!default'})   ? 1 : 0 }
124
125 sub accessor  { $_[0]->{'$!accessor'}  }
126 sub reader    { $_[0]->{'$!reader'}    }
127 sub writer    { $_[0]->{'$!writer'}    }
128 sub predicate { $_[0]->{'$!predicate'} }
129 sub clearer   { $_[0]->{'$!clearer'}   }
130 sub builder   { $_[0]->{'$!builder'}   }
131 sub init_arg  { $_[0]->{'$!init_arg'}  }
132
133 # end bootstrapped away method section.
134 # (all methods below here are kept intact)
135
136 sub get_read_method  { 
137     my $self   = shift;    
138     my $reader = $self->reader || $self->accessor;
139     # normal case ...
140     return $reader unless ref $reader;
141     # the HASH ref case
142     my ($name) = %$reader;
143     return $name;
144 }
145
146 sub get_write_method { 
147     my $self   = shift;
148     my $writer = $self->writer || $self->accessor; 
149     # normal case ...
150     return $writer unless ref $writer;
151     # the HASH ref case
152     my ($name) = %$writer;
153     return $name;    
154 }
155
156 sub get_read_method_ref {
157     my $self = shift;
158     if ((my $reader = $self->get_read_method) && $self->associated_class) {   
159         return $self->associated_class->get_method($reader);
160     }
161     else {
162         return sub { $self->get_value(@_) };
163     }
164 }
165
166 sub get_write_method_ref {
167     my $self = shift;    
168     if ((my $writer = $self->get_write_method) && $self->associated_class) {         
169         return $self->associated_class->get_method($writer);
170     }
171     else {
172         return sub { $self->set_value(@_) };
173     }
174 }
175
176 sub is_default_a_coderef {
177     ('CODE' eq (reftype($_[0]->{'$!default'} || $_[0]->{default}) || ''))
178 }
179
180 sub default {
181     my ($self, $instance) = @_;
182     if (defined $instance && $self->is_default_a_coderef) {
183         # if the default is a CODE ref, then
184         # we pass in the instance and default
185         # can return a value based on that
186         # instance. Somewhat crude, but works.
187         return $self->{'$!default'}->($instance);
188     }
189     $self->{'$!default'};
190 }
191
192 # slots
193
194 sub slots { (shift)->name }
195
196 # class association
197
198 sub attach_to_class {
199     my ($self, $class) = @_;
200     (blessed($class) && $class->isa('Class::MOP::Class'))
201         || confess "You must pass a Class::MOP::Class instance (or a subclass)";
202     weaken($self->{'$!associated_class'} = $class);
203 }
204
205 sub detach_from_class {
206     my $self = shift;
207     $self->{'$!associated_class'} = undef;
208 }
209
210 # method association
211
212 sub associate_method {
213     my ($self, $method) = @_;
214     push @{$self->{'@!associated_methods'}} => $method;
215 }
216
217 ## Slot management
218
219 sub set_value {
220     my ($self, $instance, $value) = @_;
221
222     Class::MOP::Class->initialize(blessed($instance))
223                      ->get_meta_instance
224                      ->set_slot_value($instance, $self->name, $value);
225 }
226
227 sub get_value {
228     my ($self, $instance) = @_;
229
230     Class::MOP::Class->initialize(blessed($instance))
231                      ->get_meta_instance
232                      ->get_slot_value($instance, $self->name);
233 }
234
235 sub has_value {
236     my ($self, $instance) = @_;
237
238     Class::MOP::Class->initialize(blessed($instance))
239                      ->get_meta_instance
240                      ->is_slot_initialized($instance, $self->name);
241 }
242
243 sub clear_value {
244     my ($self, $instance) = @_;
245
246     Class::MOP::Class->initialize(blessed($instance))
247                      ->get_meta_instance
248                      ->deinitialize_slot($instance, $self->name);
249 }
250
251 ## load em up ...
252
253 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
254
255 sub process_accessors {
256     my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
257     if (reftype($accessor)) {
258         (reftype($accessor) eq 'HASH')
259             || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
260         my ($name, $method) = %{$accessor};
261         $method = $self->accessor_metaclass->wrap($method);
262         $self->associate_method($method);
263         return ($name, $method);
264     }
265     else {
266         my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
267         my $method;
268         eval {
269             $method = $self->accessor_metaclass->new(
270                 attribute     => $self,
271                 is_inline     => $inline_me,
272                 accessor_type => $type,
273             );
274         };
275         confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
276         $self->associate_method($method);
277         return ($accessor, $method);
278     }
279 }
280
281 sub install_accessors {
282     my $self   = shift;
283     my $inline = shift;
284     my $class  = $self->associated_class;
285
286     $class->add_method(
287         $self->process_accessors('accessor' => $self->accessor(), $inline)
288     ) if $self->has_accessor();
289
290     $class->add_method(
291         $self->process_accessors('reader' => $self->reader(), $inline)
292     ) if $self->has_reader();
293
294     $class->add_method(
295         $self->process_accessors('writer' => $self->writer(), $inline)
296     ) if $self->has_writer();
297
298     $class->add_method(
299         $self->process_accessors('predicate' => $self->predicate(), $inline)
300     ) if $self->has_predicate();
301
302     $class->add_method(
303         $self->process_accessors('clearer' => $self->clearer(), $inline)
304     ) if $self->has_clearer();
305
306     return;
307 }
308
309 {
310     my $_remove_accessor = sub {
311         my ($accessor, $class) = @_;
312         if (reftype($accessor) && reftype($accessor) eq 'HASH') {
313             ($accessor) = keys %{$accessor};
314         }
315         my $method = $class->get_method($accessor);
316         $class->remove_method($accessor)
317             if (blessed($method) && $method->isa('Class::MOP::Method::Accessor'));
318     };
319
320     sub remove_accessors {
321         my $self = shift;
322         # TODO:
323         # we really need to make sure to remove from the
324         # associates methods here as well. But this is
325         # such a slimly used method, I am not worried
326         # about it right now.
327         $_remove_accessor->($self->accessor(),  $self->associated_class()) if $self->has_accessor();
328         $_remove_accessor->($self->reader(),    $self->associated_class()) if $self->has_reader();
329         $_remove_accessor->($self->writer(),    $self->associated_class()) if $self->has_writer();
330         $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
331         $_remove_accessor->($self->clearer(),   $self->associated_class()) if $self->has_clearer();
332         return;
333     }
334
335 }
336
337 1;
338
339 __END__
340
341 =pod
342
343 =head1 NAME
344
345 Class::MOP::Attribute - Attribute Meta Object
346
347 =head1 SYNOPSIS
348
349   Class::MOP::Attribute->new('$foo' => (
350       accessor  => 'foo',        # dual purpose get/set accessor
351       predicate => 'has_foo'     # predicate check for defined-ness
352       init_arg  => '-foo',       # class->new will look for a -foo key
353       default   => 'BAR IS BAZ!' # if no -foo key is provided, use this
354   ));
355
356   Class::MOP::Attribute->new('$.bar' => (
357       reader    => 'bar',        # getter
358       writer    => 'set_bar',    # setter
359       predicate => 'has_bar'     # predicate check for defined-ness
360       init_arg  => ':bar',       # class->new will look for a :bar key
361       # no default value means it is undef
362   ));
363
364 =head1 DESCRIPTION
365
366 The Attribute Protocol is almost entirely an invention of this module,
367 and is completely optional to this MOP. This is because Perl 5 does not
368 have consistent notion of what is an attribute of a class. There are
369 so many ways in which this is done, and very few (if any) are
370 easily discoverable by this module.
371
372 So, all that said, this module attempts to inject some order into this
373 chaos, by introducing a consistent API which can be used to create
374 object attributes.
375
376 =head1 METHODS
377
378 =head2 Creation
379
380 =over 4
381
382 =item B<new ($name, ?%options)>
383
384 An attribute must (at the very least), have a C<$name>. All other
385 C<%options> are contained added as key-value pairs. Acceptable keys
386 are as follows:
387
388 =over 4
389
390 =item I<init_arg>
391
392 This should be a string value representing the expected key in
393 an initialization hash. For instance, if we have an I<init_arg>
394 value of C<-foo>, then the following code will Just Work.
395
396   MyClass->meta->construct_instance(-foo => "Hello There");
397
398 In an init_arg is not assigned, it will automatically use the
399 value of C<$name>.
400
401 =item I<builder>
402
403 The value of this key is the name of the method that will be
404 called to obtain the value used to initialize the attribute.
405 This should be a method in the class associated with the attribute,
406 not a method in the attribute class itself.
407
408 =item I<default>
409
410 The value of this key is the default value which
411 C<Class::MOP::Class::construct_instance> will initialize the
412 attribute to.
413
414 B<NOTE:>
415 If the value is a simple scalar (string or number), then it can
416 be just passed as is. However, if you wish to initialize it with
417 a HASH or ARRAY ref, then you need to wrap that inside a CODE
418 reference, like so:
419
420   Class::MOP::Attribute->new('@foo' => (
421       default => sub { [] },
422   ));
423
424   # or ...
425
426   Class::MOP::Attribute->new('%foo' => (
427       default => sub { {} },
428   ));
429
430 If you wish to initialize an attribute with a CODE reference
431 itself, then you need to wrap that in a subroutine as well, like
432 so:
433
434   Class::MOP::Attribute->new('&foo' => (
435       default => sub { sub { print "Hello World" } },
436   ));
437
438 And lastly, if the value of your attribute is dependent upon
439 some other aspect of the instance structure, then you can take
440 advantage of the fact that when the I<default> value is a CODE
441 reference, it is passed the raw (unblessed) instance structure
442 as it's only argument. So you can do things like this:
443
444   Class::MOP::Attribute->new('$object_identity' => (
445       default => sub { Scalar::Util::refaddr($_[0]) },
446   ));
447
448 This last feature is fairly limited as there is no gurantee of
449 the order of attribute initializations, so you cannot perform
450 any kind of dependent initializations. However, if this is
451 something you need, you could subclass B<Class::MOP::Class> and
452 this class to acheive it. However, this is currently left as
453 an exercise to the reader :).
454
455 =back
456
457 The I<accessor>, I<reader>, I<writer>, I<predicate> and I<clearer> keys can
458 contain either; the name of the method and an appropriate default one will be
459 generated for you, B<or> a HASH ref containing exactly one key (which will be
460 used as the name of the method) and one value, which should contain a CODE
461 reference which will be installed as the method itself.
462
463 =over 4
464
465 =item I<accessor>
466
467 The I<accessor> is a standard perl-style read/write accessor. It will
468 return the value of the attribute, and if a value is passed as an argument,
469 it will assign that value to the attribute.
470
471 B<NOTE:>
472 This method will properly handle the following code, by assigning an
473 C<undef> value to the attribute.
474
475   $object->set_something(undef);
476
477 =item I<reader>
478
479 This is a basic read-only accessor, it will just return the value of
480 the attribute.
481
482 =item I<writer>
483
484 This is a basic write accessor, it accepts a single argument, and
485 assigns that value to the attribute. This method does not intentially
486 return a value, however perl will return the result of the last
487 expression in the subroutine, which returns in this returning the
488 same value that it was passed.
489
490 B<NOTE:>
491 This method will properly handle the following code, by assigning an
492 C<undef> value to the attribute.
493
494   $object->set_something();
495
496 =item I<predicate>
497
498 This is a basic test to see if any value has been set for the 
499 attribute. It will return true (C<1>) if the attribute has been set 
500 to any value (even C<undef>), and false (C<0>) otherwise.
501
502 B<NOTE:>
503 The predicate will return true even when you set an attribute's
504 value to C<undef>. This behaviour has changed as of version 0.43. In 
505 older versions, the predicate (erroneously) checked for attribute 
506 value definedness, instead of presence as it is now.
507
508 If you really want to get rid of the value, you have to define and 
509 use a I<clearer> (see below).
510
511
512 =item I<clearer>
513
514 This is the a method that will uninitialize the attr, reverting lazy values
515 back to their "unfulfilled" state.
516
517 =back
518
519 =item B<clone (%options)>
520
521 =item B<initialize_instance_slot ($instance, $params)>
522
523 =back
524
525 =head2 Value management
526
527 These methods are basically "backdoors" to the instance, which can be used
528 to bypass the regular accessors, but still stay within the context of the MOP.
529
530 These methods are not for general use, and should only be used if you really
531 know what you are doing.
532
533 =over 4
534
535 =item B<set_value ($instance, $value)>
536
537 Set the value without going through the accessor. Note that this may be done to
538 even attributes with just read only accessors.
539
540 =item B<get_value ($instance)>
541
542 Return the value without going through the accessor. Note that this may be done
543 even to attributes with just write only accessors.
544
545 =item B<has_value ($instance)>
546
547 Return a boolean indicating if the item in the C<$instance> has a value in it.
548 This is basically what the default C<predicate> method calls.
549
550 =item B<clear_value ($instance)>
551
552 This will clear the value in the C<$instance>. This is basically what the default
553 C<clearer> would call. Note that this may be done even if the attirbute does not
554 have any associated read, write or clear methods.
555
556 =back
557
558 =head2 Informational
559
560 These are all basic read-only value accessors for the values
561 passed into C<new>. I think they are pretty much self-explanitory.
562
563 =over 4
564
565 =item B<name>
566
567 =item B<accessor>
568
569 =item B<reader>
570
571 =item B<writer>
572
573 =item B<predicate>
574
575 =item B<clearer>
576
577 =item B<init_arg>
578
579 =item B<is_default_a_coderef>
580
581 =item B<default (?$instance)>
582
583 Return the default value for the attribute.
584
585 If you pass in an C<$instance> argument to this accessor and the
586 I<default> is a CODE reference, then the CODE reference will be
587 executed with the C<$instance> as its argument.
588
589 =item B<slots>
590
591 Return a list of slots required by the attribute. This is usually
592 just one, which is the name of the attribute.
593
594 =item B<get_read_method>
595
596 =item B<get_write_method>
597
598 Return the name of a method name suitable for reading / writing the value 
599 of the attribute in the associated class. Suitable for use whether 
600 C<reader> and C<writer> or C<accessor> was used.
601
602 =item B<get_read_method_ref>
603
604 =item B<get_write_method_ref>
605
606 Return the CODE reference of a method suitable for reading / writing the 
607 value of the attribute in the associated class. Suitable for use whether 
608 C<reader> and C<writer> or C<accessor> was specified or not.
609
610 NOTE: If not reader/writer/accessor was specified, this will use the 
611 attribute get_value/set_value methods, which can be very inefficient.
612
613 =back
614
615 =head2 Informational predicates
616
617 These are all basic predicate methods for the values passed into C<new>.
618
619 =over 4
620
621 =item B<has_accessor>
622
623 =item B<has_reader>
624
625 =item B<has_writer>
626
627 =item B<has_predicate>
628
629 =item B<has_clearer>
630
631 =item B<has_init_arg>
632
633 =item B<has_default>
634
635 =item B<has_builder>
636
637 =back
638
639 =head2 Class association
640
641 These methods allow you to manage the attributes association with
642 the class that contains it. These methods should not be used
643 lightly, nor are they very magical, they are mostly used internally
644 and by metaclass instances.
645
646 =over 4
647
648 =item B<associated_class>
649
650 This returns the metaclass this attribute is associated with.
651
652 =item B<attach_to_class ($class)>
653
654 This will store a weaken reference to C<$class> internally. You should
655 note that just changing the class assocation will not remove the attribute
656 from it's old class, and initialize it (and it's accessors) in the new
657 C<$class>. It is up to you to do this manually.
658
659 =item B<detach_from_class>
660
661 This will remove the weakened reference to the class. It does B<not>
662 remove the attribute itself from the class (or remove it's accessors),
663 you must do that yourself if you want too. Actually if that is what
664 you want to do, you should probably be looking at
665 L<Class::MOP::Class::remove_attribute> instead.
666
667 =back
668
669 =head2 Attribute Accessor generation
670
671 =over 4
672
673 =item B<accessor_metaclass>
674
675 Accessors are generated by an accessor metaclass, which is usually
676 a subclass of C<Class::MOP::Method::Accessor>. This method returns
677 the name of the accessor metaclass that this attribute uses.
678
679 =item B<associate_method ($method)>
680
681 This will associate a C<$method> with the given attribute which is
682 used internally by the accessor generator.
683
684 =item B<associated_methods>
685
686 This will return the list of methods which have been associated with
687 the C<associate_method> methods.
688
689 =item B<install_accessors>
690
691 This allows the attribute to generate and install code for it's own
692 I<accessor/reader/writer/predicate> methods. This is called by
693 C<Class::MOP::Class::add_attribute>.
694
695 This method will call C<process_accessors> for each of the possible
696 method types (accessor, reader, writer & predicate).
697
698 =item B<process_accessors ($type, $value)>
699
700 This takes a C<$type> (accessor, reader, writer or predicate), and
701 a C<$value> (the value passed into the constructor for each of the
702 different types). It will then either generate the method itself
703 (using the C<generate_*_method> methods listed below) or it will
704 use the custom method passed through the constructor.
705
706 =item B<remove_accessors>
707
708 This allows the attribute to remove the method for it's own
709 I<accessor/reader/writer/predicate/clearer>. This is called by
710 C<Class::MOP::Class::remove_attribute>.
711
712 NOTE: This does not currently remove methods from the list returned
713 by C<associated_methods>, that is on the TODO list.
714
715 =back
716
717 =head2 Introspection
718
719 =over 4
720
721 =item B<meta>
722
723 This will return a B<Class::MOP::Class> instance which is related
724 to this class.
725
726 It should also be noted that B<Class::MOP> will actually bootstrap
727 this module by installing a number of attribute meta-objects into
728 it's metaclass. This will allow this class to reap all the benifits
729 of the MOP when subclassing it.
730
731 =back
732
733 =head1 AUTHORS
734
735 Stevan Little E<lt>stevan@iinteractive.comE<gt>
736
737 =head1 COPYRIGHT AND LICENSE
738
739 Copyright 2006-2008 by Infinity Interactive, Inc.
740
741 L<http://www.iinteractive.com>
742
743 This library is free software; you can redistribute it and/or modify
744 it under the same terms as Perl itself.
745
746 =cut
747
748