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