2 package Class::MOP::Attribute;
7 use Class::MOP::Method::Accessor;
10 use Scalar::Util 'blessed', 'reftype', 'weaken';
12 our $VERSION = '0.19';
13 our $AUTHORITY = 'cpan:STEVAN';
15 use base 'Class::MOP::Object';
18 require Class::MOP::Class;
19 Class::MOP::Class->initialize(blessed($_[0]) || $_[0]);
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
30 # - Ain't meta-circularity grand? :)
36 (defined $name && $name)
37 || confess "You must provide a name for the attribute";
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};
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};
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' => [],
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.
80 || confess "Can only clone an instance";
81 return bless { %{$self}, %options } => blessed($self);
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 ...
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});
94 elsif (defined $self->{'$!default'}) {
95 $meta_instance->set_slot_value($instance, $self->name, $self->default($instance));
97 elsif (defined( my $builder = $self->{'$!builder'})) {
98 if ($builder = $instance->can($builder)) {
99 $meta_instance->set_slot_value($instance, $self->name, $instance->$builder);
102 confess(blessed($instance)." does not support builder method '". $self->{'$!builder'} ."' for attribute '" . $self->name . "'");
108 # the next bunch of methods will get bootstrapped
109 # away in the Class::MOP bootstrapping section
111 sub name { $_[0]->{'$!name'} }
113 sub associated_class { $_[0]->{'$!associated_class'} }
114 sub associated_methods { $_[0]->{'@!associated_methods'} }
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 }
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'} }
133 # end bootstrapped away method section.
134 # (all methods below here are kept intact)
136 sub get_read_method { $_[0]->reader || $_[0]->accessor }
137 sub get_write_method { $_[0]->writer || $_[0]->accessor }
139 sub get_read_method_ref {
141 if ((my $reader = $self->get_read_method) && $self->associated_class) {
142 return $self->associated_class->get_method($reader);
145 return sub { $self->get_value(@_) };
149 sub get_write_method_ref {
151 if ((my $writer = $self->get_write_method) && $self->associated_class) {
152 return $self->associated_class->get_method($writer);
155 return sub { $self->set_value(@_) };
159 sub is_default_a_coderef {
160 ('CODE' eq (reftype($_[0]->{'$!default'} || $_[0]->{default}) || ''))
164 my ($self, $instance) = @_;
165 if (defined $instance && $self->is_default_a_coderef) {
166 # if the default is a CODE ref, then
167 # we pass in the instance and default
168 # can return a value based on that
169 # instance. Somewhat crude, but works.
170 return $self->{'$!default'}->($instance);
172 $self->{'$!default'};
177 sub slots { (shift)->name }
181 sub attach_to_class {
182 my ($self, $class) = @_;
183 (blessed($class) && $class->isa('Class::MOP::Class'))
184 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
185 weaken($self->{'$!associated_class'} = $class);
188 sub detach_from_class {
190 $self->{'$!associated_class'} = undef;
195 sub associate_method {
196 my ($self, $method) = @_;
197 push @{$self->{'@!associated_methods'}} => $method;
203 my ($self, $instance, $value) = @_;
205 Class::MOP::Class->initialize(blessed($instance))
207 ->set_slot_value($instance, $self->name, $value);
211 my ($self, $instance) = @_;
213 Class::MOP::Class->initialize(blessed($instance))
215 ->get_slot_value($instance, $self->name);
219 my ($self, $instance) = @_;
221 Class::MOP::Class->initialize(blessed($instance))
223 ->is_slot_initialized($instance, $self->name);
227 my ($self, $instance) = @_;
229 Class::MOP::Class->initialize(blessed($instance))
231 ->deinitialize_slot($instance, $self->name);
236 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
238 sub process_accessors {
239 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
240 if (reftype($accessor)) {
241 (reftype($accessor) eq 'HASH')
242 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
243 my ($name, $method) = %{$accessor};
244 $method = $self->accessor_metaclass->wrap($method);
245 $self->associate_method($method);
246 return ($name, $method);
249 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
252 $method = $self->accessor_metaclass->new(
254 is_inline => $inline_me,
255 accessor_type => $type,
258 confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
259 $self->associate_method($method);
260 return ($accessor, $method);
264 sub install_accessors {
267 my $class = $self->associated_class;
270 $self->process_accessors('accessor' => $self->accessor(), $inline)
271 ) if $self->has_accessor();
274 $self->process_accessors('reader' => $self->reader(), $inline)
275 ) if $self->has_reader();
278 $self->process_accessors('writer' => $self->writer(), $inline)
279 ) if $self->has_writer();
282 $self->process_accessors('predicate' => $self->predicate(), $inline)
283 ) if $self->has_predicate();
286 $self->process_accessors('clearer' => $self->clearer(), $inline)
287 ) if $self->has_clearer();
293 my $_remove_accessor = sub {
294 my ($accessor, $class) = @_;
295 if (reftype($accessor) && reftype($accessor) eq 'HASH') {
296 ($accessor) = keys %{$accessor};
298 my $method = $class->get_method($accessor);
299 $class->remove_method($accessor)
300 if (blessed($method) && $method->isa('Class::MOP::Method::Accessor'));
303 sub remove_accessors {
306 # we really need to make sure to remove from the
307 # associates methods here as well. But this is
308 # such a slimly used method, I am not worried
309 # about it right now.
310 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
311 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
312 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
313 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
314 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
328 Class::MOP::Attribute - Attribute Meta Object
332 Class::MOP::Attribute->new('$foo' => (
333 accessor => 'foo', # dual purpose get/set accessor
334 predicate => 'has_foo' # predicate check for defined-ness
335 init_arg => '-foo', # class->new will look for a -foo key
336 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
339 Class::MOP::Attribute->new('$.bar' => (
340 reader => 'bar', # getter
341 writer => 'set_bar', # setter
342 predicate => 'has_bar' # predicate check for defined-ness
343 init_arg => ':bar', # class->new will look for a :bar key
344 # no default value means it is undef
349 The Attribute Protocol is almost entirely an invention of this module,
350 and is completely optional to this MOP. This is because Perl 5 does not
351 have consistent notion of what is an attribute of a class. There are
352 so many ways in which this is done, and very few (if any) are
353 easily discoverable by this module.
355 So, all that said, this module attempts to inject some order into this
356 chaos, by introducing a consistent API which can be used to create
365 =item B<new ($name, ?%options)>
367 An attribute must (at the very least), have a C<$name>. All other
368 C<%options> are contained added as key-value pairs. Acceptable keys
375 This should be a string value representing the expected key in
376 an initialization hash. For instance, if we have an I<init_arg>
377 value of C<-foo>, then the following code will Just Work.
379 MyClass->meta->construct_instance(-foo => "Hello There");
381 In an init_arg is not assigned, it will automatically use the
386 The value of this key is the default value which
387 C<Class::MOP::Class::construct_instance> will initialize the
392 The value of this key is the name of the method that will be
393 called to obtain the value used to initialize the attribute.
394 This should be a method in the class associated with the attribute,
395 not a method in the attribute class itself.
398 If the value is a simple scalar (string or number), then it can
399 be just passed as is. However, if you wish to initialize it with
400 a HASH or ARRAY ref, then you need to wrap that inside a CODE
403 Class::MOP::Attribute->new('@foo' => (
404 default => sub { [] },
409 Class::MOP::Attribute->new('%foo' => (
410 default => sub { {} },
413 If you wish to initialize an attribute with a CODE reference
414 itself, then you need to wrap that in a subroutine as well, like
417 Class::MOP::Attribute->new('&foo' => (
418 default => sub { sub { print "Hello World" } },
421 And lastly, if the value of your attribute is dependent upon
422 some other aspect of the instance structure, then you can take
423 advantage of the fact that when the I<default> value is a CODE
424 reference, it is passed the raw (unblessed) instance structure
425 as it's only argument. So you can do things like this:
427 Class::MOP::Attribute->new('$object_identity' => (
428 default => sub { Scalar::Util::refaddr($_[0]) },
431 This last feature is fairly limited as there is no gurantee of
432 the order of attribute initializations, so you cannot perform
433 any kind of dependent initializations. However, if this is
434 something you need, you could subclass B<Class::MOP::Class> and
435 this class to acheive it. However, this is currently left as
436 an exercise to the reader :).
440 The I<accessor>, I<reader>, I<writer>, I<predicate> and I<clearer> keys can
441 contain either; the name of the method and an appropriate default one will be
442 generated for you, B<or> a HASH ref containing exactly one key (which will be
443 used as the name of the method) and one value, which should contain a CODE
444 reference which will be installed as the method itself.
450 The I<accessor> is a standard perl-style read/write accessor. It will
451 return the value of the attribute, and if a value is passed as an argument,
452 it will assign that value to the attribute.
455 This method will properly handle the following code, by assigning an
456 C<undef> value to the attribute.
458 $object->set_something(undef);
462 This is a basic read-only accessor, it will just return the value of
467 This is a basic write accessor, it accepts a single argument, and
468 assigns that value to the attribute. This method does not intentially
469 return a value, however perl will return the result of the last
470 expression in the subroutine, which returns in this returning the
471 same value that it was passed.
474 This method will properly handle the following code, by assigning an
475 C<undef> value to the attribute.
477 $object->set_something();
481 This is a basic test to see if the value of the attribute is not
482 C<undef>. It will return true (C<1>) if the attribute's value is
483 defined, and false (C<0>) otherwise.
487 This is the a method that will uninitialize the attr, reverting lazy values
488 back to their "unfulfilled" state.
492 =item B<clone (%options)>
494 =item B<initialize_instance_slot ($instance, $params)>
498 =head2 Value management
500 These methods are basically "backdoors" to the instance, which can be used
501 to bypass the regular accessors, but still stay within the context of the MOP.
503 These methods are not for general use, and should only be used if you really
504 know what you are doing.
508 =item B<set_value ($instance, $value)>
510 Set the value without going through the accessor. Note that this may be done to
511 even attributes with just read only accessors.
513 =item B<get_value ($instance)>
515 Return the value without going through the accessor. Note that this may be done
516 even to attributes with just write only accessors.
518 =item B<has_value ($instance)>
520 Returns a boolean indicating if the item in the C<$instance> has a value in it.
521 This is basically what the default C<predicate> method calls.
523 =item B<clear_value ($instance)>
525 This will clear the value in the C<$instance>. This is basically what the default
526 C<clearer> would call. Note that this may be done even if the attirbute does not
527 have any associated read, write or clear methods.
533 These are all basic read-only value accessors for the values
534 passed into C<new>. I think they are pretty much self-explanitory.
552 =item B<is_default_a_coderef>
554 =item B<default (?$instance)>
556 As noted in the documentation for C<new> above, if the I<default>
557 value is a CODE reference, this accessor will pass a single additional
558 argument C<$instance> into it and return the value.
562 Returns a list of slots required by the attribute. This is usually
563 just one, which is the name of the attribute.
565 =item B<get_read_method>
567 =item B<get_write_method>
569 Return the name of a method name suitable for reading / writing the value
570 of the attribute in the associated class. Suitable for use whether
571 C<reader> and C<writer> or C<accessor> was used.
573 =item B<get_read_method_ref>
575 =item B<get_write_method_ref>
577 Return the CODE reference of a method suitable for reading / writing the
578 value of the attribute in the associated class. Suitable for use whether
579 C<reader> and C<writer> or C<accessor> was specified or not.
581 NOTE: If not reader/writer/accessor was specified, this will use the
582 attribute get_value/set_value methods, which can be very inefficient.
586 =head2 Informational predicates
588 These are all basic predicate methods for the values passed into C<new>.
592 =item B<has_accessor>
598 =item B<has_predicate>
602 =item B<has_init_arg>
610 =head2 Class association
612 These methods allow you to manage the attributes association with
613 the class that contains it. These methods should not be used
614 lightly, nor are they very magical, they are mostly used internally
615 and by metaclass instances.
619 =item B<associated_class>
621 This returns the metaclass this attribute is associated with.
623 =item B<attach_to_class ($class)>
625 This will store a weaken reference to C<$class> internally. You should
626 note that just changing the class assocation will not remove the attribute
627 from it's old class, and initialize it (and it's accessors) in the new
628 C<$class>. It is up to you to do this manually.
630 =item B<detach_from_class>
632 This will remove the weakened reference to the class. It does B<not>
633 remove the attribute itself from the class (or remove it's accessors),
634 you must do that yourself if you want too. Actually if that is what
635 you want to do, you should probably be looking at
636 L<Class::MOP::Class::remove_attribute> instead.
640 =head2 Attribute Accessor generation
644 =item B<accessor_metaclass>
646 Accessors are generated by an accessor metaclass, which is usually
647 a subclass of C<Class::MOP::Method::Accessor>. This method returns
648 the name of the accessor metaclass that this attribute uses.
650 =item B<associate_method ($method)>
652 This will associate a C<$method> with the given attribute which is
653 used internally by the accessor generator.
655 =item B<associated_methods>
657 This will return the list of methods which have been associated with
658 the C<associate_method> methods.
660 =item B<install_accessors>
662 This allows the attribute to generate and install code for it's own
663 I<accessor/reader/writer/predicate> methods. This is called by
664 C<Class::MOP::Class::add_attribute>.
666 This method will call C<process_accessors> for each of the possible
667 method types (accessor, reader, writer & predicate).
669 =item B<process_accessors ($type, $value)>
671 This takes a C<$type> (accessor, reader, writer or predicate), and
672 a C<$value> (the value passed into the constructor for each of the
673 different types). It will then either generate the method itself
674 (using the C<generate_*_method> methods listed below) or it will
675 use the custom method passed through the constructor.
677 =item B<remove_accessors>
679 This allows the attribute to remove the method for it's own
680 I<accessor/reader/writer/predicate/clearer>. This is called by
681 C<Class::MOP::Class::remove_attribute>.
683 NOTE: This does not currently remove methods from the list returned
684 by C<associated_methods>, that is on the TODO list.
694 This will return a B<Class::MOP::Class> instance which is related
697 It should also be noted that B<Class::MOP> will actually bootstrap
698 this module by installing a number of attribute meta-objects into
699 it's metaclass. This will allow this class to reap all the benifits
700 of the MOP when subclassing it.
706 Stevan Little E<lt>stevan@iinteractive.comE<gt>
708 =head1 COPYRIGHT AND LICENSE
710 Copyright 2006, 2007 by Infinity Interactive, Inc.
712 L<http://www.iinteractive.com>
714 This library is free software; you can redistribute it and/or modify
715 it under the same terms as Perl itself.