2 package Class::MOP::Attribute;
7 use Class::MOP::Method::Accessor;
10 use Scalar::Util 'blessed', 'reftype', 'weaken';
12 our $VERSION = '0.24';
13 our $AUTHORITY = 'cpan:STEVAN';
15 use base 'Class::MOP::Object';
17 # NOTE: (meta-circularity)
18 # This method will be replaced in the
19 # boostrap section of Class::MOP, by
20 # a new version which uses the
21 # &Class::MOP::Class::construct_instance
22 # method to build an attribute meta-object
23 # which itself is described with attribute
25 # - Ain't meta-circularity grand? :)
31 (defined $name && $name)
32 || confess "You must provide a name for the attribute";
34 $options{init_arg} = $name
35 if not exists $options{init_arg};
36 if(exists $options{builder}){
37 confess("builder must be a defined scalar value which is a method name")
38 if ref $options{builder} || !(defined $options{builder});
39 confess("Setting both default and builder is not allowed.")
40 if exists $options{default};
42 (is_default_a_coderef(\%options))
43 || confess("References are not allowed as default values, you must ".
44 "wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])")
45 if exists $options{default} && ref $options{default};
47 if( $options{required} and not( defined($options{builder}) || defined($options{init_arg}) || exists $options{default} ) ) {
48 confess("A required attribute must have either 'init_arg', 'builder', or 'default'");
52 '$!accessor' => $options{accessor},
53 '$!reader' => $options{reader},
54 '$!writer' => $options{writer},
55 '$!predicate' => $options{predicate},
56 '$!clearer' => $options{clearer},
57 '$!builder' => $options{builder},
58 '$!init_arg' => $options{init_arg},
59 '$!default' => $options{default},
60 '$!initializer' => $options{initializer},
61 # keep a weakened link to the
62 # class we are associated with
63 '$!associated_class' => undef,
64 # and a list of the methods
65 # associated with this attr
66 '@!associated_methods' => [],
68 # protect this from silliness
74 # this is a primative (and kludgy) clone operation
75 # for now, it will be replaced in the Class::MOP
76 # bootstrap with a proper one, however we know
77 # that this one will work fine for now.
82 || confess "Can only clone an instance";
83 return bless { %{$self}, %options } => blessed($self);
86 sub initialize_instance_slot {
87 my ($self, $meta_instance, $instance, $params) = @_;
88 my $init_arg = $self->{'$!init_arg'};
89 # try to fetch the init arg from the %params ...
91 # if nothing was in the %params, we can use the
92 # attribute's default value (if it has one)
93 if(defined $init_arg and exists $params->{$init_arg}){
94 $self->_set_initial_slot_value(
100 elsif (defined $self->{'$!default'}) {
101 $self->_set_initial_slot_value(
104 $self->default($instance),
107 elsif (defined( my $builder = $self->{'$!builder'})) {
108 if ($builder = $instance->can($builder)) {
109 $self->_set_initial_slot_value(
116 confess(blessed($instance)." does not support builder method '". $self->{'$!builder'} ."' for attribute '" . $self->name . "'");
121 sub _set_initial_slot_value {
122 my ($self, $meta_instance, $instance, $value) = @_;
124 my $slot_name = $self->name;
126 return $meta_instance->set_slot_value($instance, $slot_name, $value)
127 unless $self->has_initializer;
130 $meta_instance->set_slot_value($instance, $slot_name, $_[0]);
133 my $initializer = $self->initializer;
135 # most things will just want to set a value, so make it first arg
136 $instance->$initializer($value, $callback, $self);
140 # the next bunch of methods will get bootstrapped
141 # away in the Class::MOP bootstrapping section
143 sub name { $_[0]->{'$!name'} }
145 sub associated_class { $_[0]->{'$!associated_class'} }
146 sub associated_methods { $_[0]->{'@!associated_methods'} }
148 sub has_accessor { defined($_[0]->{'$!accessor'}) ? 1 : 0 }
149 sub has_reader { defined($_[0]->{'$!reader'}) ? 1 : 0 }
150 sub has_writer { defined($_[0]->{'$!writer'}) ? 1 : 0 }
151 sub has_predicate { defined($_[0]->{'$!predicate'}) ? 1 : 0 }
152 sub has_clearer { defined($_[0]->{'$!clearer'}) ? 1 : 0 }
153 sub has_builder { defined($_[0]->{'$!builder'}) ? 1 : 0 }
154 sub has_init_arg { defined($_[0]->{'$!init_arg'}) ? 1 : 0 }
155 sub has_default { defined($_[0]->{'$!default'}) ? 1 : 0 }
156 sub has_initializer { defined($_[0]->{'$!initializer'}) ? 1 : 0 }
158 sub accessor { $_[0]->{'$!accessor'} }
159 sub reader { $_[0]->{'$!reader'} }
160 sub writer { $_[0]->{'$!writer'} }
161 sub predicate { $_[0]->{'$!predicate'} }
162 sub clearer { $_[0]->{'$!clearer'} }
163 sub builder { $_[0]->{'$!builder'} }
164 sub init_arg { $_[0]->{'$!init_arg'} }
165 sub initializer { $_[0]->{'$!initializer'} }
167 # end bootstrapped away method section.
168 # (all methods below here are kept intact)
170 sub has_read_method { $_[0]->has_reader || $_[0]->has_accessor }
171 sub has_write_method { $_[0]->has_writer || $_[0]->has_accessor }
173 sub get_read_method {
175 my $reader = $self->reader || $self->accessor;
177 return $reader unless ref $reader;
179 my ($name) = %$reader;
183 sub get_write_method {
185 my $writer = $self->writer || $self->accessor;
187 return $writer unless ref $writer;
189 my ($name) = %$writer;
193 sub get_read_method_ref {
195 if ((my $reader = $self->get_read_method) && $self->associated_class) {
196 return $self->associated_class->get_method($reader);
199 return sub { $self->get_value(@_) };
203 sub get_write_method_ref {
205 if ((my $writer = $self->get_write_method) && $self->associated_class) {
206 return $self->associated_class->get_method($writer);
209 return sub { $self->set_value(@_) };
213 sub is_default_a_coderef {
214 ('CODE' eq (reftype($_[0]->{'$!default'} || $_[0]->{default}) || ''))
218 my ($self, $instance) = @_;
219 if (defined $instance && $self->is_default_a_coderef) {
220 # if the default is a CODE ref, then
221 # we pass in the instance and default
222 # can return a value based on that
223 # instance. Somewhat crude, but works.
224 return $self->{'$!default'}->($instance);
226 $self->{'$!default'};
231 sub slots { (shift)->name }
235 sub attach_to_class {
236 my ($self, $class) = @_;
237 (blessed($class) && $class->isa('Class::MOP::Class'))
238 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
239 weaken($self->{'$!associated_class'} = $class);
242 sub detach_from_class {
244 $self->{'$!associated_class'} = undef;
249 sub associate_method {
250 my ($self, $method) = @_;
251 push @{$self->{'@!associated_methods'}} => $method;
256 sub set_initial_value {
257 my ($self, $instance, $value) = @_;
258 $self->_set_initial_slot_value(
259 Class::MOP::Class->initialize(blessed($instance))->get_meta_instance,
266 my ($self, $instance, $value) = @_;
268 Class::MOP::Class->initialize(blessed($instance))
270 ->set_slot_value($instance, $self->name, $value);
274 my ($self, $instance) = @_;
276 Class::MOP::Class->initialize(blessed($instance))
278 ->get_slot_value($instance, $self->name);
282 my ($self, $instance) = @_;
284 Class::MOP::Class->initialize(blessed($instance))
286 ->is_slot_initialized($instance, $self->name);
290 my ($self, $instance) = @_;
292 Class::MOP::Class->initialize(blessed($instance))
294 ->deinitialize_slot($instance, $self->name);
299 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
301 sub process_accessors {
302 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
303 if (reftype($accessor)) {
304 (reftype($accessor) eq 'HASH')
305 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
306 my ($name, $method) = %{$accessor};
307 $method = $self->accessor_metaclass->wrap(
309 package_name => $self->associated_class->name,
312 $self->associate_method($method);
313 return ($name, $method);
316 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
319 $method = $self->accessor_metaclass->new(
321 is_inline => $inline_me,
322 accessor_type => $type,
323 package_name => $self->associated_class->name,
327 confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
328 $self->associate_method($method);
329 return ($accessor, $method);
333 sub install_accessors {
336 my $class = $self->associated_class;
339 $self->process_accessors('accessor' => $self->accessor(), $inline)
340 ) if $self->has_accessor();
343 $self->process_accessors('reader' => $self->reader(), $inline)
344 ) if $self->has_reader();
347 $self->process_accessors('writer' => $self->writer(), $inline)
348 ) if $self->has_writer();
351 $self->process_accessors('predicate' => $self->predicate(), $inline)
352 ) if $self->has_predicate();
355 $self->process_accessors('clearer' => $self->clearer(), $inline)
356 ) if $self->has_clearer();
362 my $_remove_accessor = sub {
363 my ($accessor, $class) = @_;
364 if (reftype($accessor) && reftype($accessor) eq 'HASH') {
365 ($accessor) = keys %{$accessor};
367 my $method = $class->get_method($accessor);
368 $class->remove_method($accessor)
369 if (blessed($method) && $method->isa('Class::MOP::Method::Accessor'));
372 sub remove_accessors {
375 # we really need to make sure to remove from the
376 # associates methods here as well. But this is
377 # such a slimly used method, I am not worried
378 # about it right now.
379 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
380 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
381 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
382 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
383 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
397 Class::MOP::Attribute - Attribute Meta Object
401 Class::MOP::Attribute->new('$foo' => (
402 accessor => 'foo', # dual purpose get/set accessor
403 predicate => 'has_foo' # predicate check for defined-ness
404 init_arg => '-foo', # class->new will look for a -foo key
405 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
408 Class::MOP::Attribute->new('$.bar' => (
409 reader => 'bar', # getter
410 writer => 'set_bar', # setter
411 predicate => 'has_bar' # predicate check for defined-ness
412 init_arg => ':bar', # class->new will look for a :bar key
413 # no default value means it is undef
418 The Attribute Protocol is almost entirely an invention of this module,
419 and is completely optional to this MOP. This is because Perl 5 does not
420 have consistent notion of what is an attribute of a class. There are
421 so many ways in which this is done, and very few (if any) are
422 easily discoverable by this module.
424 So, all that said, this module attempts to inject some order into this
425 chaos, by introducing a consistent API which can be used to create
434 =item B<new ($name, ?%options)>
436 An attribute must (at the very least), have a C<$name>. All other
437 C<%options> are contained added as key-value pairs. Acceptable keys
444 This should be a string value representing the expected key in
445 an initialization hash. For instance, if we have an I<init_arg>
446 value of C<-foo>, then the following code will Just Work.
448 MyClass->meta->construct_instance(-foo => "Hello There");
450 In an init_arg is not assigned, it will automatically use the
451 value of C<$name>. If an explicit C<undef> is given for an init_arg,
452 an attribute value can't be specified during initialization.
456 The value of this key is the name of the method that will be
457 called to obtain the value used to initialize the attribute.
458 This should be a method in the class associated with the attribute,
459 not a method in the attribute class itself.
463 The value of this key is the default value which
464 C<Class::MOP::Class::construct_instance> will initialize the
468 If the value is a simple scalar (string or number), then it can
469 be just passed as is. However, if you wish to initialize it with
470 a HASH or ARRAY ref, then you need to wrap that inside a CODE
473 Class::MOP::Attribute->new('@foo' => (
474 default => sub { [] },
479 Class::MOP::Attribute->new('%foo' => (
480 default => sub { {} },
483 If you wish to initialize an attribute with a CODE reference
484 itself, then you need to wrap that in a subroutine as well, like
487 Class::MOP::Attribute->new('&foo' => (
488 default => sub { sub { print "Hello World" } },
491 And lastly, if the value of your attribute is dependent upon
492 some other aspect of the instance structure, then you can take
493 advantage of the fact that when the I<default> value is a CODE
494 reference, it is passed the (as yet unfinished) instance structure
495 as it's only argument. So you can do things like this:
497 Class::MOP::Attribute->new('$object_identity' => (
498 default => sub { Scalar::Util::refaddr($_[0]) },
501 This last feature is fairly limited as there is no gurantee of
502 the order of attribute initializations, so you cannot perform
503 any kind of dependent initializations. However, if this is
504 something you need, you could subclass B<Class::MOP::Class> and
505 this class to acheive it. However, this is currently left as
506 an exercise to the reader :).
510 This may be a method name (referring to a method on the class with this
511 attribute) or a CODE ref. The initializer is used to set the attribute value
512 on an instance when the attribute is set during instance initialization. When
513 called, it is passed the instance (as the invocant), the value to set, a
514 slot-setting CODE ref, and the attribute meta-instance. The slot-setting code
515 is provided to make it easy to set the (possibly altered) value on the instance
516 without going through several more method calls.
518 This contrived example shows an initializer that sets the attribute to twice
521 Class::MOP::Attribute->new('$doubled' => (
523 my ($instance, $value, $set) = @_;
528 As method names can be given as initializers, one can easily make
529 attribute initialization use the writer:
531 Class::MOP::Attribute->new('$some_attr' => (
532 writer => 'some_attr',
533 initializer => 'some_attr',
536 Your writer will simply need to examine it's C<@_> and determine under
537 which context it is being called.
541 The I<accessor>, I<reader>, I<writer>, I<predicate> and I<clearer> keys can
542 contain either; the name of the method and an appropriate default one will be
543 generated for you, B<or> a HASH ref containing exactly one key (which will be
544 used as the name of the method) and one value, which should contain a CODE
545 reference which will be installed as the method itself.
551 The I<accessor> is a standard perl-style read/write accessor. It will
552 return the value of the attribute, and if a value is passed as an argument,
553 it will assign that value to the attribute.
556 This method will properly handle the following code, by assigning an
557 C<undef> value to the attribute.
559 $object->set_something(undef);
563 This is a basic read-only accessor, it will just return the value of
568 This is a basic write accessor, it accepts a single argument, and
569 assigns that value to the attribute. This method does not intentially
570 return a value, however perl will return the result of the last
571 expression in the subroutine, which returns in this returning the
572 same value that it was passed.
575 This method will properly handle the following code, by assigning an
576 C<undef> value to the attribute.
578 $object->set_something();
582 This is a basic test to see if any value has been set for the
583 attribute. It will return true (C<1>) if the attribute has been set
584 to any value (even C<undef>), and false (C<0>) otherwise.
587 The predicate will return true even when you set an attribute's
588 value to C<undef>. This behaviour has changed as of version 0.43. In
589 older versions, the predicate (erroneously) checked for attribute
590 value definedness, instead of presence as it is now.
592 If you really want to get rid of the value, you have to define and
593 use a I<clearer> (see below).
597 This is the a method that will uninitialize the attr, reverting lazy values
598 back to their "unfulfilled" state.
602 =item B<clone (%options)>
604 This will return a clone of the attribute instance, allowing the overriding
605 of various attributes through the C<%options> supplied.
607 =item B<initialize_instance_slot ($instance, $params)>
609 This method is used internally to initialize the approriate slot for this
610 attribute in a given C<$instance>, the C<$params> passed are those that were
611 passed to the constructor.
615 =head2 Value management
617 These methods are basically "backdoors" to the instance, which can be used
618 to bypass the regular accessors, but still stay within the context of the MOP.
620 These methods are not for general use, and should only be used if you really
621 know what you are doing.
625 =item B<set_value ($instance, $value)>
627 Set the value without going through the accessor. Note that this may be done to
628 even attributes with just read only accessors.
630 =item B<set_initial_value ($instance, $value)>
632 This method sets the value without going through the accessor -- but it is only
633 called when the instance data is first initialized.
635 =item B<get_value ($instance)>
637 Return the value without going through the accessor. Note that this may be done
638 even to attributes with just write only accessors.
640 =item B<has_value ($instance)>
642 Return a boolean indicating if the item in the C<$instance> has a value in it.
643 This is basically what the default C<predicate> method calls.
645 =item B<clear_value ($instance)>
647 This will clear the value in the C<$instance>. This is basically what the default
648 C<clearer> would call. Note that this may be done even if the attirbute does not
649 have any associated read, write or clear methods.
655 These are all basic read-only value accessors for the values
656 passed into C<new>. I think they are pretty much self-explanitory.
676 =item B<is_default_a_coderef>
678 =item B<default (?$instance)>
680 Return the default value for the attribute.
682 If you pass in an C<$instance> argument to this accessor and the
683 I<default> is a CODE reference, then the CODE reference will be
684 executed with the C<$instance> as its argument.
688 Return a list of slots required by the attribute. This is usually
689 just one, which is the name of the attribute.
691 =item B<get_read_method>
693 =item B<get_write_method>
695 Return the name of a method name suitable for reading / writing the value
696 of the attribute in the associated class. Suitable for use whether
697 C<reader> and C<writer> or C<accessor> was used.
699 =item B<get_read_method_ref>
701 =item B<get_write_method_ref>
703 Return the CODE reference of a method suitable for reading / writing the
704 value of the attribute in the associated class. Suitable for use whether
705 C<reader> and C<writer> or C<accessor> was specified or not.
707 NOTE: If no reader/writer/accessor was specified, this will use the
708 attribute get_value/set_value methods, which can be very inefficient.
710 =item B<has_read_method>
712 =item B<has_write_method>
714 Return whether a method exists suitable for reading / writing the value
715 of the attribute in the associated class. Suitable for use whether
716 C<reader> and C<writer> or C<accessor> was used.
720 =head2 Informational predicates
722 These are all basic predicate methods for the values passed into C<new>.
726 =item B<has_accessor>
732 =item B<has_predicate>
736 =item B<has_initializer>
738 =item B<has_init_arg>
746 =head2 Class association
748 These methods allow you to manage the attributes association with
749 the class that contains it. These methods should not be used
750 lightly, nor are they very magical, they are mostly used internally
751 and by metaclass instances.
755 =item B<associated_class>
757 This returns the metaclass this attribute is associated with.
759 =item B<attach_to_class ($class)>
761 This will store a weaken reference to C<$class> internally. You should
762 note that just changing the class assocation will not remove the attribute
763 from it's old class, and initialize it (and it's accessors) in the new
764 C<$class>. It is up to you to do this manually.
766 =item B<detach_from_class>
768 This will remove the weakened reference to the class. It does B<not>
769 remove the attribute itself from the class (or remove it's accessors),
770 you must do that yourself if you want too. Actually if that is what
771 you want to do, you should probably be looking at
772 L<Class::MOP::Class::remove_attribute> instead.
776 =head2 Attribute Accessor generation
780 =item B<accessor_metaclass>
782 Accessors are generated by an accessor metaclass, which is usually
783 a subclass of C<Class::MOP::Method::Accessor>. This method returns
784 the name of the accessor metaclass that this attribute uses.
786 =item B<associate_method ($method)>
788 This will associate a C<$method> with the given attribute which is
789 used internally by the accessor generator.
791 =item B<associated_methods>
793 This will return the list of methods which have been associated with
794 the C<associate_method> methods. This is a good way of seeing what
795 methods are used to manage a given attribute.
797 =item B<install_accessors>
799 This allows the attribute to generate and install code for it's own
800 I<accessor/reader/writer/predicate> methods. This is called by
801 C<Class::MOP::Class::add_attribute>.
803 This method will call C<process_accessors> for each of the possible
804 method types (accessor, reader, writer & predicate).
806 =item B<process_accessors ($type, $value)>
808 This takes a C<$type> (accessor, reader, writer or predicate), and
809 a C<$value> (the value passed into the constructor for each of the
810 different types). It will then either generate the method itself
811 (using the C<generate_*_method> methods listed below) or it will
812 use the custom method passed through the constructor.
814 =item B<remove_accessors>
816 This allows the attribute to remove the method for it's own
817 I<accessor/reader/writer/predicate/clearer>. This is called by
818 C<Class::MOP::Class::remove_attribute>.
820 NOTE: This does not currently remove methods from the list returned
821 by C<associated_methods>, that is on the TODO list.
831 This will return a B<Class::MOP::Class> instance which is related
834 It should also be noted that B<Class::MOP> will actually bootstrap
835 this module by installing a number of attribute meta-objects into
836 it's metaclass. This will allow this class to reap all the benefits
837 of the MOP when subclassing it.
843 Stevan Little E<lt>stevan@iinteractive.comE<gt>
845 =head1 COPYRIGHT AND LICENSE
847 Copyright 2006-2008 by Infinity Interactive, Inc.
849 L<http://www.iinteractive.com>
851 This library is free software; you can redistribute it and/or modify
852 it under the same terms as Perl itself.