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