2 package Class::MOP::Attribute;
7 use Class::MOP::Method::Accessor;
10 use Scalar::Util 'blessed', 'weaken';
12 our $VERSION = '0.65';
13 $VERSION = eval $VERSION;
14 our $AUTHORITY = 'cpan:STEVAN';
16 use base 'Class::MOP::Object';
18 # NOTE: (meta-circularity)
19 # This method will be replaced in the
20 # boostrap section of Class::MOP, by
21 # a new version which uses the
22 # &Class::MOP::Class::construct_instance
23 # method to build an attribute meta-object
24 # which itself is described with attribute
26 # - Ain't meta-circularity grand? :)
28 my ( $class, @args ) = @_;
30 unshift @args, "name" if @args % 2 == 1;
33 my $name = $options{name};
35 (defined $name && $name)
36 || confess "You must provide a name for the attribute";
38 $options{init_arg} = $name
39 if not exists $options{init_arg};
40 if(exists $options{builder}){
41 confess("builder must be a defined scalar value which is a method name")
42 if ref $options{builder} || !(defined $options{builder});
43 confess("Setting both default and builder is not allowed.")
44 if exists $options{default};
46 (is_default_a_coderef(\%options))
47 || confess("References are not allowed as default values, you must ".
48 "wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])")
49 if exists $options{default} && ref $options{default};
51 if( $options{required} and not( defined($options{builder}) || defined($options{init_arg}) || exists $options{default} ) ) {
52 confess("A required attribute must have either 'init_arg', 'builder', or 'default'");
55 $class->_new(\%options);
60 my $options = @_ == 1 ? $_[0] : {@_};
63 'name' => $options->{name},
64 'accessor' => $options->{accessor},
65 'reader' => $options->{reader},
66 'writer' => $options->{writer},
67 'predicate' => $options->{predicate},
68 'clearer' => $options->{clearer},
69 'builder' => $options->{builder},
70 'init_arg' => $options->{init_arg},
71 'default' => $options->{default},
72 'initializer' => $options->{initializer},
73 # keep a weakened link to the
74 # class we are associated with
75 'associated_class' => undef,
76 # and a list of the methods
77 # associated with this attr
78 'associated_methods' => [],
83 # this is a primative (and kludgy) clone operation
84 # for now, it will be replaced in the Class::MOP
85 # bootstrap with a proper one, however we know
86 # that this one will work fine for now.
91 || confess "Can only clone an instance";
92 return bless { %{$self}, %options } => ref($self);
95 sub initialize_instance_slot {
96 my ($self, $meta_instance, $instance, $params) = @_;
97 my $init_arg = $self->{'init_arg'};
99 # try to fetch the init arg from the %params ...
101 # if nothing was in the %params, we can use the
102 # attribute's default value (if it has one)
103 if(defined $init_arg and exists $params->{$init_arg}){
104 $self->_set_initial_slot_value(
107 $params->{$init_arg},
110 elsif (defined $self->{'default'}) {
111 $self->_set_initial_slot_value(
114 $self->default($instance),
117 elsif (defined( my $builder = $self->{'builder'})) {
118 if ($builder = $instance->can($builder)) {
119 $self->_set_initial_slot_value(
126 confess(ref($instance)." does not support builder method '". $self->{'builder'} ."' for attribute '" . $self->name . "'");
131 sub _set_initial_slot_value {
132 my ($self, $meta_instance, $instance, $value) = @_;
134 my $slot_name = $self->name;
136 return $meta_instance->set_slot_value($instance, $slot_name, $value)
137 unless $self->has_initializer;
140 $meta_instance->set_slot_value($instance, $slot_name, $_[0]);
143 my $initializer = $self->initializer;
145 # most things will just want to set a value, so make it first arg
146 $instance->$initializer($value, $callback, $self);
150 # the next bunch of methods will get bootstrapped
151 # away in the Class::MOP bootstrapping section
153 sub name { $_[0]->{'name'} }
155 sub associated_class { $_[0]->{'associated_class'} }
156 sub associated_methods { $_[0]->{'associated_methods'} }
158 sub has_accessor { defined($_[0]->{'accessor'}) }
159 sub has_reader { defined($_[0]->{'reader'}) }
160 sub has_writer { defined($_[0]->{'writer'}) }
161 sub has_predicate { defined($_[0]->{'predicate'}) }
162 sub has_clearer { defined($_[0]->{'clearer'}) }
163 sub has_builder { defined($_[0]->{'builder'}) }
164 sub has_init_arg { defined($_[0]->{'init_arg'}) }
165 sub has_default { defined($_[0]->{'default'}) }
166 sub has_initializer { defined($_[0]->{'initializer'}) }
168 sub accessor { $_[0]->{'accessor'} }
169 sub reader { $_[0]->{'reader'} }
170 sub writer { $_[0]->{'writer'} }
171 sub predicate { $_[0]->{'predicate'} }
172 sub clearer { $_[0]->{'clearer'} }
173 sub builder { $_[0]->{'builder'} }
174 sub init_arg { $_[0]->{'init_arg'} }
175 sub initializer { $_[0]->{'initializer'} }
177 # end bootstrapped away method section.
178 # (all methods below here are kept intact)
180 sub has_read_method { $_[0]->has_reader || $_[0]->has_accessor }
181 sub has_write_method { $_[0]->has_writer || $_[0]->has_accessor }
183 sub get_read_method {
185 my $reader = $self->reader || $self->accessor;
187 return $reader unless ref $reader;
189 my ($name) = %$reader;
193 sub get_write_method {
195 my $writer = $self->writer || $self->accessor;
197 return $writer unless ref $writer;
199 my ($name) = %$writer;
203 sub get_read_method_ref {
205 if ((my $reader = $self->get_read_method) && $self->associated_class) {
206 return $self->associated_class->get_method($reader);
209 my $code = sub { $self->get_value(@_) };
210 if (my $class = $self->associated_class) {
211 return $class->method_metaclass->wrap(
213 package_name => $class->name,
223 sub get_write_method_ref {
225 if ((my $writer = $self->get_write_method) && $self->associated_class) {
226 return $self->associated_class->get_method($writer);
229 my $code = sub { $self->set_value(@_) };
230 if (my $class = $self->associated_class) {
231 return $class->method_metaclass->wrap(
233 package_name => $class->name,
243 sub is_default_a_coderef {
244 ('CODE' eq ref($_[0]->{'default'} || $_[0]->{default}))
248 my ($self, $instance) = @_;
249 if (defined $instance && $self->is_default_a_coderef) {
250 # if the default is a CODE ref, then
251 # we pass in the instance and default
252 # can return a value based on that
253 # instance. Somewhat crude, but works.
254 return $self->{'default'}->($instance);
261 sub slots { (shift)->name }
265 sub attach_to_class {
266 my ($self, $class) = @_;
267 (blessed($class) && $class->isa('Class::MOP::Class'))
268 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
269 weaken($self->{'associated_class'} = $class);
272 sub detach_from_class {
274 $self->{'associated_class'} = undef;
279 sub associate_method {
280 my ($self, $method) = @_;
281 push @{$self->{'associated_methods'}} => $method;
286 sub set_initial_value {
287 my ($self, $instance, $value) = @_;
288 $self->_set_initial_slot_value(
289 Class::MOP::Class->initialize(ref($instance))->get_meta_instance,
296 my ($self, $instance, $value) = @_;
298 Class::MOP::Class->initialize(ref($instance))
300 ->set_slot_value($instance, $self->name, $value);
304 my ($self, $instance) = @_;
306 Class::MOP::Class->initialize(ref($instance))
308 ->get_slot_value($instance, $self->name);
312 my ($self, $instance) = @_;
314 Class::MOP::Class->initialize(ref($instance))
316 ->is_slot_initialized($instance, $self->name);
320 my ($self, $instance) = @_;
322 Class::MOP::Class->initialize(ref($instance))
324 ->deinitialize_slot($instance, $self->name);
329 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
331 sub process_accessors {
332 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
333 if (ref($accessor)) {
334 (ref($accessor) eq 'HASH')
335 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
336 my ($name, $method) = %{$accessor};
337 $method = $self->accessor_metaclass->wrap(
339 package_name => $self->associated_class->name,
342 $self->associate_method($method);
343 return ($name, $method);
346 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
349 $method = $self->accessor_metaclass->new(
351 is_inline => $inline_me,
352 accessor_type => $type,
353 package_name => $self->associated_class->name,
357 confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
358 $self->associate_method($method);
359 return ($accessor, $method);
363 sub install_accessors {
366 my $class = $self->associated_class;
369 $self->process_accessors('accessor' => $self->accessor(), $inline)
370 ) if $self->has_accessor();
373 $self->process_accessors('reader' => $self->reader(), $inline)
374 ) if $self->has_reader();
377 $self->process_accessors('writer' => $self->writer(), $inline)
378 ) if $self->has_writer();
381 $self->process_accessors('predicate' => $self->predicate(), $inline)
382 ) if $self->has_predicate();
385 $self->process_accessors('clearer' => $self->clearer(), $inline)
386 ) if $self->has_clearer();
392 my $_remove_accessor = sub {
393 my ($accessor, $class) = @_;
394 if (ref($accessor) && ref($accessor) eq 'HASH') {
395 ($accessor) = keys %{$accessor};
397 my $method = $class->get_method($accessor);
398 $class->remove_method($accessor)
399 if (ref($method) && $method->isa('Class::MOP::Method::Accessor'));
402 sub remove_accessors {
405 # we really need to make sure to remove from the
406 # associates methods here as well. But this is
407 # such a slimly used method, I am not worried
408 # about it right now.
409 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
410 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
411 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
412 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
413 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
427 Class::MOP::Attribute - Attribute Meta Object
431 Class::MOP::Attribute->new( foo => (
432 accessor => 'foo', # dual purpose get/set accessor
433 predicate => 'has_foo' # predicate check for defined-ness
434 init_arg => '-foo', # class->new will look for a -foo key
435 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
438 Class::MOP::Attribute->new( bar => (
439 reader => 'bar', # getter
440 writer => 'set_bar', # setter
441 predicate => 'has_bar' # predicate check for defined-ness
442 init_arg => ':bar', # class->new will look for a :bar key
443 # no default value means it is undef
448 The Attribute Protocol is almost entirely an invention of this module,
449 and is completely optional to this MOP. This is because Perl 5 does not
450 have consistent notion of what is an attribute of a class. There are
451 so many ways in which this is done, and very few (if any) are
452 easily discoverable by this module.
454 So, all that said, this module attempts to inject some order into this
455 chaos, by introducing a consistent API which can be used to create
464 =item B<new ($name, ?%options)>
466 An attribute must (at the very least), have a C<$name>. All other
467 C<%options> are contained added as key-value pairs. Acceptable keys
474 This should be a string value representing the expected key in
475 an initialization hash. For instance, if we have an I<init_arg>
476 value of C<-foo>, then the following code will Just Work.
478 MyClass->meta->construct_instance(-foo => "Hello There");
480 In an init_arg is not assigned, it will automatically use the
481 value of C<$name>. If an explicit C<undef> is given for an init_arg,
482 an attribute value can't be specified during initialization.
486 The value of this key is the name of the method that will be
487 called to obtain the value used to initialize the attribute.
488 This should be a method in the class associated with the attribute,
489 not a method in the attribute class itself.
493 The value of this key is the default value which
494 C<Class::MOP::Class::construct_instance> will initialize the
498 If the value is a simple scalar (string or number), then it can
499 be just passed as is. However, if you wish to initialize it with
500 a HASH or ARRAY ref, then you need to wrap that inside a CODE
503 Class::MOP::Attribute->new('@foo' => (
504 default => sub { [] },
509 Class::MOP::Attribute->new('%foo' => (
510 default => sub { {} },
513 If you wish to initialize an attribute with a CODE reference
514 itself, then you need to wrap that in a subroutine as well, like
517 Class::MOP::Attribute->new('&foo' => (
518 default => sub { sub { print "Hello World" } },
521 And lastly, if the value of your attribute is dependent upon
522 some other aspect of the instance structure, then you can take
523 advantage of the fact that when the I<default> value is a CODE
524 reference, it is passed the (as yet unfinished) instance structure
525 as it's only argument. So you can do things like this:
527 Class::MOP::Attribute->new('$object_identity' => (
528 default => sub { Scalar::Util::refaddr($_[0]) },
531 This last feature is fairly limited as there is no gurantee of
532 the order of attribute initializations, so you cannot perform
533 any kind of dependent initializations. However, if this is
534 something you need, you could subclass B<Class::MOP::Class> and
535 this class to acheive it. However, this is currently left as
536 an exercise to the reader :).
540 This may be a method name (referring to a method on the class with this
541 attribute) or a CODE ref. The initializer is used to set the attribute value
542 on an instance when the attribute is set during instance initialization. When
543 called, it is passed the instance (as the invocant), the value to set, a
544 slot-setting CODE ref, and the attribute meta-instance. The slot-setting code
545 is provided to make it easy to set the (possibly altered) value on the instance
546 without going through several more method calls.
548 This contrived example shows an initializer that sets the attribute to twice
551 Class::MOP::Attribute->new('$doubled' => (
553 my ($instance, $value, $set) = @_;
558 As method names can be given as initializers, one can easily make
559 attribute initialization use the writer:
561 Class::MOP::Attribute->new('$some_attr' => (
562 writer => 'some_attr',
563 initializer => 'some_attr',
566 Your writer will simply need to examine it's C<@_> and determine under
567 which context it is being called.
571 The I<accessor>, I<reader>, I<writer>, I<predicate> and I<clearer> keys can
572 contain either; the name of the method and an appropriate default one will be
573 generated for you, B<or> a HASH ref containing exactly one key (which will be
574 used as the name of the method) and one value, which should contain a CODE
575 reference which will be installed as the method itself.
581 The I<accessor> is a standard perl-style read/write accessor. It will
582 return the value of the attribute, and if a value is passed as an argument,
583 it will assign that value to the attribute.
586 This method will properly handle the following code, by assigning an
587 C<undef> value to the attribute.
589 $object->set_something(undef);
593 This is a basic read-only accessor, it will just return the value of
598 This is a basic write accessor, it accepts a single argument, and
599 assigns that value to the attribute. This method does not intentially
600 return a value, however perl will return the result of the last
601 expression in the subroutine, which returns in this returning the
602 same value that it was passed.
605 This method will properly handle the following code, by assigning an
606 C<undef> value to the attribute.
608 $object->set_something();
612 This is a basic test to see if any value has been set for the
613 attribute. It will return true (C<1>) if the attribute has been set
614 to any value (even C<undef>), and false (C<0>) otherwise.
617 The predicate will return true even when you set an attribute's
618 value to C<undef>. This behaviour has changed as of version 0.43. In
619 older versions, the predicate (erroneously) checked for attribute
620 value definedness, instead of presence as it is now.
622 If you really want to get rid of the value, you have to define and
623 use a I<clearer> (see below).
627 This is the a method that will uninitialize the attr, reverting lazy values
628 back to their "unfulfilled" state.
632 =item B<clone (%options)>
634 This will return a clone of the attribute instance, allowing the overriding
635 of various attributes through the C<%options> supplied.
637 =item B<initialize_instance_slot ($instance, $params)>
639 This method is used internally to initialize the approriate slot for this
640 attribute in a given C<$instance>, the C<$params> passed are those that were
641 passed to the constructor.
645 =head2 Value management
647 These methods are basically "backdoors" to the instance, which can be used
648 to bypass the regular accessors, but still stay within the context of the MOP.
650 These methods are not for general use, and should only be used if you really
651 know what you are doing.
655 =item B<set_value ($instance, $value)>
657 Set the value without going through the accessor. Note that this may be done to
658 even attributes with just read only accessors.
660 =item B<set_initial_value ($instance, $value)>
662 This method sets the value without going through the accessor -- but it is only
663 called when the instance data is first initialized.
665 =item B<get_value ($instance)>
667 Return the value without going through the accessor. Note that this may be done
668 even to attributes with just write only accessors.
670 =item B<has_value ($instance)>
672 Return a boolean indicating if the item in the C<$instance> has a value in it.
673 This is basically what the default C<predicate> method calls.
675 =item B<clear_value ($instance)>
677 This will clear the value in the C<$instance>. This is basically what the default
678 C<clearer> would call. Note that this may be done even if the attirbute does not
679 have any associated read, write or clear methods.
685 These are all basic read-only value accessors for the values
686 passed into C<new>. I think they are pretty much self-explanitory.
706 =item B<is_default_a_coderef>
708 =item B<default (?$instance)>
710 Return the default value for the attribute.
712 If you pass in an C<$instance> argument to this accessor and the
713 I<default> is a CODE reference, then the CODE reference will be
714 executed with the C<$instance> as its argument.
718 Return a list of slots required by the attribute. This is usually
719 just one, which is the name of the attribute.
721 =item B<get_read_method>
723 =item B<get_write_method>
725 Return the name of a method name suitable for reading / writing the value
726 of the attribute in the associated class. Suitable for use whether
727 C<reader> and C<writer> or C<accessor> was used.
729 =item B<get_read_method_ref>
731 =item B<get_write_method_ref>
733 Return the CODE reference of a method suitable for reading / writing the
734 value of the attribute in the associated class. Suitable for use whether
735 C<reader> and C<writer> or C<accessor> was specified or not.
737 NOTE: If no reader/writer/accessor was specified, this will use the
738 attribute get_value/set_value methods, which can be very inefficient.
740 =item B<has_read_method>
742 =item B<has_write_method>
744 Return whether a method exists suitable for reading / writing the value
745 of the attribute in the associated class. Suitable for use whether
746 C<reader> and C<writer> or C<accessor> was used.
750 =head2 Informational predicates
752 These are all basic predicate methods for the values passed into C<new>.
756 =item B<has_accessor>
762 =item B<has_predicate>
766 =item B<has_initializer>
768 =item B<has_init_arg>
776 =head2 Class association
778 These methods allow you to manage the attributes association with
779 the class that contains it. These methods should not be used
780 lightly, nor are they very magical, they are mostly used internally
781 and by metaclass instances.
785 =item B<associated_class>
787 This returns the metaclass this attribute is associated with.
789 =item B<attach_to_class ($class)>
791 This will store a weaken reference to C<$class> internally. You should
792 note that just changing the class assocation will not remove the attribute
793 from it's old class, and initialize it (and it's accessors) in the new
794 C<$class>. It is up to you to do this manually.
796 =item B<detach_from_class>
798 This will remove the weakened reference to the class. It does B<not>
799 remove the attribute itself from the class (or remove it's accessors),
800 you must do that yourself if you want too. Actually if that is what
801 you want to do, you should probably be looking at
802 L<Class::MOP::Class::remove_attribute> instead.
806 =head2 Attribute Accessor generation
810 =item B<accessor_metaclass>
812 Accessors are generated by an accessor metaclass, which is usually
813 a subclass of C<Class::MOP::Method::Accessor>. This method returns
814 the name of the accessor metaclass that this attribute uses.
816 =item B<associate_method ($method)>
818 This will associate a C<$method> with the given attribute which is
819 used internally by the accessor generator.
821 =item B<associated_methods>
823 This will return the list of methods which have been associated with
824 the C<associate_method> methods. This is a good way of seeing what
825 methods are used to manage a given attribute.
827 =item B<install_accessors>
829 This allows the attribute to generate and install code for it's own
830 I<accessor/reader/writer/predicate> methods. This is called by
831 C<Class::MOP::Class::add_attribute>.
833 This method will call C<process_accessors> for each of the possible
834 method types (accessor, reader, writer & predicate).
836 =item B<process_accessors ($type, $value)>
838 This takes a C<$type> (accessor, reader, writer or predicate), and
839 a C<$value> (the value passed into the constructor for each of the
840 different types). It will then either generate the method itself
841 (using the C<generate_*_method> methods listed below) or it will
842 use the custom method passed through the constructor.
844 =item B<remove_accessors>
846 This allows the attribute to remove the method for it's own
847 I<accessor/reader/writer/predicate/clearer>. This is called by
848 C<Class::MOP::Class::remove_attribute>.
850 NOTE: This does not currently remove methods from the list returned
851 by C<associated_methods>, that is on the TODO list.
861 This will return a B<Class::MOP::Class> instance which is related
864 It should also be noted that B<Class::MOP> will actually bootstrap
865 this module by installing a number of attribute meta-objects into
866 it's metaclass. This will allow this class to reap all the benefits
867 of the MOP when subclassing it.
873 Stevan Little E<lt>stevan@iinteractive.comE<gt>
875 =head1 COPYRIGHT AND LICENSE
877 Copyright 2006-2008 by Infinity Interactive, Inc.
879 L<http://www.iinteractive.com>
881 This library is free software; you can redistribute it and/or modify
882 it under the same terms as Perl itself.