2 package Class::MOP::Attribute;
7 use Class::MOP::Method::Accessor;
10 use Scalar::Util 'blessed', 'weaken';
12 our $VERSION = '0.65';
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'");
53 'accessor' => $options{accessor},
54 'reader' => $options{reader},
55 'writer' => $options{writer},
56 'predicate' => $options{predicate},
57 'clearer' => $options{clearer},
58 'builder' => $options{builder},
59 'init_arg' => $options{init_arg},
60 'default' => $options{default},
61 'initializer' => $options{initializer},
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'};
88 # try to fetch the init arg from the %params ...
90 # if nothing was in the %params, we can use the
91 # attribute's default value (if it has one)
92 if(defined $init_arg and exists $params->{$init_arg}){
93 $self->_set_initial_slot_value(
99 elsif (defined $self->{'default'}) {
100 $self->_set_initial_slot_value(
103 $self->default($instance),
106 elsif (defined( my $builder = $self->{'builder'})) {
107 if ($builder = $instance->can($builder)) {
108 $self->_set_initial_slot_value(
115 confess(blessed($instance)." does not support builder method '". $self->{'builder'} ."' for attribute '" . $self->name . "'");
120 sub _set_initial_slot_value {
121 my ($self, $meta_instance, $instance, $value) = @_;
123 my $slot_name = $self->name;
125 return $meta_instance->set_slot_value($instance, $slot_name, $value)
126 unless $self->has_initializer;
129 $meta_instance->set_slot_value($instance, $slot_name, $_[0]);
132 my $initializer = $self->initializer;
134 # most things will just want to set a value, so make it first arg
135 $instance->$initializer($value, $callback, $self);
139 # the next bunch of methods will get bootstrapped
140 # away in the Class::MOP bootstrapping section
142 sub name { $_[0]->{'name'} }
144 sub associated_class { $_[0]->{'associated_class'} }
145 sub associated_methods { $_[0]->{'associated_methods'} }
147 sub has_accessor { defined($_[0]->{'accessor'}) ? 1 : 0 }
148 sub has_reader { defined($_[0]->{'reader'}) ? 1 : 0 }
149 sub has_writer { defined($_[0]->{'writer'}) ? 1 : 0 }
150 sub has_predicate { defined($_[0]->{'predicate'}) ? 1 : 0 }
151 sub has_clearer { defined($_[0]->{'clearer'}) ? 1 : 0 }
152 sub has_builder { defined($_[0]->{'builder'}) ? 1 : 0 }
153 sub has_init_arg { defined($_[0]->{'init_arg'}) ? 1 : 0 }
154 sub has_default { defined($_[0]->{'default'}) ? 1 : 0 }
155 sub has_initializer { defined($_[0]->{'initializer'}) ? 1 : 0 }
157 sub accessor { $_[0]->{'accessor'} }
158 sub reader { $_[0]->{'reader'} }
159 sub writer { $_[0]->{'writer'} }
160 sub predicate { $_[0]->{'predicate'} }
161 sub clearer { $_[0]->{'clearer'} }
162 sub builder { $_[0]->{'builder'} }
163 sub init_arg { $_[0]->{'init_arg'} }
164 sub initializer { $_[0]->{'initializer'} }
166 # end bootstrapped away method section.
167 # (all methods below here are kept intact)
169 sub has_read_method { $_[0]->has_reader || $_[0]->has_accessor }
170 sub has_write_method { $_[0]->has_writer || $_[0]->has_accessor }
172 sub get_read_method {
174 my $reader = $self->reader || $self->accessor;
176 return $reader unless ref $reader;
178 my ($name) = %$reader;
182 sub get_write_method {
184 my $writer = $self->writer || $self->accessor;
186 return $writer unless ref $writer;
188 my ($name) = %$writer;
192 sub get_read_method_ref {
194 if ((my $reader = $self->get_read_method) && $self->associated_class) {
195 return $self->associated_class->get_method($reader);
198 my $code = sub { $self->get_value(@_) };
199 if (my $class = $self->associated_class) {
200 return $class->method_metaclass->wrap(
202 package_name => $class->name,
212 sub get_write_method_ref {
214 if ((my $writer = $self->get_write_method) && $self->associated_class) {
215 return $self->associated_class->get_method($writer);
218 my $code = sub { $self->set_value(@_) };
219 if (my $class = $self->associated_class) {
220 return $class->method_metaclass->wrap(
222 package_name => $class->name,
232 sub is_default_a_coderef {
233 ('CODE' eq ref($_[0]->{'default'} || $_[0]->{default}))
237 my ($self, $instance) = @_;
238 if (defined $instance && $self->is_default_a_coderef) {
239 # if the default is a CODE ref, then
240 # we pass in the instance and default
241 # can return a value based on that
242 # instance. Somewhat crude, but works.
243 return $self->{'default'}->($instance);
250 sub slots { (shift)->name }
254 sub attach_to_class {
255 my ($self, $class) = @_;
256 (blessed($class) && $class->isa('Class::MOP::Class'))
257 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
258 weaken($self->{'associated_class'} = $class);
261 sub detach_from_class {
263 $self->{'associated_class'} = undef;
268 sub associate_method {
269 my ($self, $method) = @_;
270 push @{$self->{'associated_methods'}} => $method;
275 sub set_initial_value {
276 my ($self, $instance, $value) = @_;
277 $self->_set_initial_slot_value(
278 Class::MOP::Class->initialize(blessed($instance))->get_meta_instance,
285 my ($self, $instance, $value) = @_;
287 Class::MOP::Class->initialize(blessed($instance))
289 ->set_slot_value($instance, $self->name, $value);
293 my ($self, $instance) = @_;
295 Class::MOP::Class->initialize(blessed($instance))
297 ->get_slot_value($instance, $self->name);
301 my ($self, $instance) = @_;
303 Class::MOP::Class->initialize(blessed($instance))
305 ->is_slot_initialized($instance, $self->name);
309 my ($self, $instance) = @_;
311 Class::MOP::Class->initialize(blessed($instance))
313 ->deinitialize_slot($instance, $self->name);
318 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
320 sub process_accessors {
321 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
322 if (ref($accessor)) {
323 (ref($accessor) eq 'HASH')
324 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
325 my ($name, $method) = %{$accessor};
326 $method = $self->accessor_metaclass->wrap(
328 package_name => $self->associated_class->name,
331 $self->associate_method($method);
332 return ($name, $method);
335 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
338 $method = $self->accessor_metaclass->new(
340 is_inline => $inline_me,
341 accessor_type => $type,
342 package_name => $self->associated_class->name,
346 confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
347 $self->associate_method($method);
348 return ($accessor, $method);
352 sub install_accessors {
355 my $class = $self->associated_class;
358 $self->process_accessors('accessor' => $self->accessor(), $inline)
359 ) if $self->has_accessor();
362 $self->process_accessors('reader' => $self->reader(), $inline)
363 ) if $self->has_reader();
366 $self->process_accessors('writer' => $self->writer(), $inline)
367 ) if $self->has_writer();
370 $self->process_accessors('predicate' => $self->predicate(), $inline)
371 ) if $self->has_predicate();
374 $self->process_accessors('clearer' => $self->clearer(), $inline)
375 ) if $self->has_clearer();
381 my $_remove_accessor = sub {
382 my ($accessor, $class) = @_;
383 if (ref($accessor) && ref($accessor) eq 'HASH') {
384 ($accessor) = keys %{$accessor};
386 my $method = $class->get_method($accessor);
387 $class->remove_method($accessor)
388 if (blessed($method) && $method->isa('Class::MOP::Method::Accessor'));
391 sub remove_accessors {
394 # we really need to make sure to remove from the
395 # associates methods here as well. But this is
396 # such a slimly used method, I am not worried
397 # about it right now.
398 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
399 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
400 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
401 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
402 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
416 Class::MOP::Attribute - Attribute Meta Object
420 Class::MOP::Attribute->new( foo => (
421 accessor => 'foo', # dual purpose get/set accessor
422 predicate => 'has_foo' # predicate check for defined-ness
423 init_arg => '-foo', # class->new will look for a -foo key
424 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
427 Class::MOP::Attribute->new( bar => (
428 reader => 'bar', # getter
429 writer => 'set_bar', # setter
430 predicate => 'has_bar' # predicate check for defined-ness
431 init_arg => ':bar', # class->new will look for a :bar key
432 # no default value means it is undef
437 The Attribute Protocol is almost entirely an invention of this module,
438 and is completely optional to this MOP. This is because Perl 5 does not
439 have consistent notion of what is an attribute of a class. There are
440 so many ways in which this is done, and very few (if any) are
441 easily discoverable by this module.
443 So, all that said, this module attempts to inject some order into this
444 chaos, by introducing a consistent API which can be used to create
453 =item B<new ($name, ?%options)>
455 An attribute must (at the very least), have a C<$name>. All other
456 C<%options> are contained added as key-value pairs. Acceptable keys
463 This should be a string value representing the expected key in
464 an initialization hash. For instance, if we have an I<init_arg>
465 value of C<-foo>, then the following code will Just Work.
467 MyClass->meta->construct_instance(-foo => "Hello There");
469 In an init_arg is not assigned, it will automatically use the
470 value of C<$name>. If an explicit C<undef> is given for an init_arg,
471 an attribute value can't be specified during initialization.
475 The value of this key is the name of the method that will be
476 called to obtain the value used to initialize the attribute.
477 This should be a method in the class associated with the attribute,
478 not a method in the attribute class itself.
482 The value of this key is the default value which
483 C<Class::MOP::Class::construct_instance> will initialize the
487 If the value is a simple scalar (string or number), then it can
488 be just passed as is. However, if you wish to initialize it with
489 a HASH or ARRAY ref, then you need to wrap that inside a CODE
492 Class::MOP::Attribute->new('@foo' => (
493 default => sub { [] },
498 Class::MOP::Attribute->new('%foo' => (
499 default => sub { {} },
502 If you wish to initialize an attribute with a CODE reference
503 itself, then you need to wrap that in a subroutine as well, like
506 Class::MOP::Attribute->new('&foo' => (
507 default => sub { sub { print "Hello World" } },
510 And lastly, if the value of your attribute is dependent upon
511 some other aspect of the instance structure, then you can take
512 advantage of the fact that when the I<default> value is a CODE
513 reference, it is passed the (as yet unfinished) instance structure
514 as it's only argument. So you can do things like this:
516 Class::MOP::Attribute->new('$object_identity' => (
517 default => sub { Scalar::Util::refaddr($_[0]) },
520 This last feature is fairly limited as there is no gurantee of
521 the order of attribute initializations, so you cannot perform
522 any kind of dependent initializations. However, if this is
523 something you need, you could subclass B<Class::MOP::Class> and
524 this class to acheive it. However, this is currently left as
525 an exercise to the reader :).
529 This may be a method name (referring to a method on the class with this
530 attribute) or a CODE ref. The initializer is used to set the attribute value
531 on an instance when the attribute is set during instance initialization. When
532 called, it is passed the instance (as the invocant), the value to set, a
533 slot-setting CODE ref, and the attribute meta-instance. The slot-setting code
534 is provided to make it easy to set the (possibly altered) value on the instance
535 without going through several more method calls.
537 This contrived example shows an initializer that sets the attribute to twice
540 Class::MOP::Attribute->new('$doubled' => (
542 my ($instance, $value, $set) = @_;
547 As method names can be given as initializers, one can easily make
548 attribute initialization use the writer:
550 Class::MOP::Attribute->new('$some_attr' => (
551 writer => 'some_attr',
552 initializer => 'some_attr',
555 Your writer will simply need to examine it's C<@_> and determine under
556 which context it is being called.
560 The I<accessor>, I<reader>, I<writer>, I<predicate> and I<clearer> keys can
561 contain either; the name of the method and an appropriate default one will be
562 generated for you, B<or> a HASH ref containing exactly one key (which will be
563 used as the name of the method) and one value, which should contain a CODE
564 reference which will be installed as the method itself.
570 The I<accessor> is a standard perl-style read/write accessor. It will
571 return the value of the attribute, and if a value is passed as an argument,
572 it will assign that value to the attribute.
575 This method will properly handle the following code, by assigning an
576 C<undef> value to the attribute.
578 $object->set_something(undef);
582 This is a basic read-only accessor, it will just return the value of
587 This is a basic write accessor, it accepts a single argument, and
588 assigns that value to the attribute. This method does not intentially
589 return a value, however perl will return the result of the last
590 expression in the subroutine, which returns in this returning the
591 same value that it was passed.
594 This method will properly handle the following code, by assigning an
595 C<undef> value to the attribute.
597 $object->set_something();
601 This is a basic test to see if any value has been set for the
602 attribute. It will return true (C<1>) if the attribute has been set
603 to any value (even C<undef>), and false (C<0>) otherwise.
606 The predicate will return true even when you set an attribute's
607 value to C<undef>. This behaviour has changed as of version 0.43. In
608 older versions, the predicate (erroneously) checked for attribute
609 value definedness, instead of presence as it is now.
611 If you really want to get rid of the value, you have to define and
612 use a I<clearer> (see below).
616 This is the a method that will uninitialize the attr, reverting lazy values
617 back to their "unfulfilled" state.
621 =item B<clone (%options)>
623 This will return a clone of the attribute instance, allowing the overriding
624 of various attributes through the C<%options> supplied.
626 =item B<initialize_instance_slot ($instance, $params)>
628 This method is used internally to initialize the approriate slot for this
629 attribute in a given C<$instance>, the C<$params> passed are those that were
630 passed to the constructor.
634 =head2 Value management
636 These methods are basically "backdoors" to the instance, which can be used
637 to bypass the regular accessors, but still stay within the context of the MOP.
639 These methods are not for general use, and should only be used if you really
640 know what you are doing.
644 =item B<set_value ($instance, $value)>
646 Set the value without going through the accessor. Note that this may be done to
647 even attributes with just read only accessors.
649 =item B<set_initial_value ($instance, $value)>
651 This method sets the value without going through the accessor -- but it is only
652 called when the instance data is first initialized.
654 =item B<get_value ($instance)>
656 Return the value without going through the accessor. Note that this may be done
657 even to attributes with just write only accessors.
659 =item B<has_value ($instance)>
661 Return a boolean indicating if the item in the C<$instance> has a value in it.
662 This is basically what the default C<predicate> method calls.
664 =item B<clear_value ($instance)>
666 This will clear the value in the C<$instance>. This is basically what the default
667 C<clearer> would call. Note that this may be done even if the attirbute does not
668 have any associated read, write or clear methods.
674 These are all basic read-only value accessors for the values
675 passed into C<new>. I think they are pretty much self-explanitory.
695 =item B<is_default_a_coderef>
697 =item B<default (?$instance)>
699 Return the default value for the attribute.
701 If you pass in an C<$instance> argument to this accessor and the
702 I<default> is a CODE reference, then the CODE reference will be
703 executed with the C<$instance> as its argument.
707 Return a list of slots required by the attribute. This is usually
708 just one, which is the name of the attribute.
710 =item B<get_read_method>
712 =item B<get_write_method>
714 Return the name of a method name 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.
718 =item B<get_read_method_ref>
720 =item B<get_write_method_ref>
722 Return the CODE reference of a method suitable for reading / writing the
723 value of the attribute in the associated class. Suitable for use whether
724 C<reader> and C<writer> or C<accessor> was specified or not.
726 NOTE: If no reader/writer/accessor was specified, this will use the
727 attribute get_value/set_value methods, which can be very inefficient.
729 =item B<has_read_method>
731 =item B<has_write_method>
733 Return whether a method exists suitable for reading / writing the value
734 of the attribute in the associated class. Suitable for use whether
735 C<reader> and C<writer> or C<accessor> was used.
739 =head2 Informational predicates
741 These are all basic predicate methods for the values passed into C<new>.
745 =item B<has_accessor>
751 =item B<has_predicate>
755 =item B<has_initializer>
757 =item B<has_init_arg>
765 =head2 Class association
767 These methods allow you to manage the attributes association with
768 the class that contains it. These methods should not be used
769 lightly, nor are they very magical, they are mostly used internally
770 and by metaclass instances.
774 =item B<associated_class>
776 This returns the metaclass this attribute is associated with.
778 =item B<attach_to_class ($class)>
780 This will store a weaken reference to C<$class> internally. You should
781 note that just changing the class assocation will not remove the attribute
782 from it's old class, and initialize it (and it's accessors) in the new
783 C<$class>. It is up to you to do this manually.
785 =item B<detach_from_class>
787 This will remove the weakened reference to the class. It does B<not>
788 remove the attribute itself from the class (or remove it's accessors),
789 you must do that yourself if you want too. Actually if that is what
790 you want to do, you should probably be looking at
791 L<Class::MOP::Class::remove_attribute> instead.
795 =head2 Attribute Accessor generation
799 =item B<accessor_metaclass>
801 Accessors are generated by an accessor metaclass, which is usually
802 a subclass of C<Class::MOP::Method::Accessor>. This method returns
803 the name of the accessor metaclass that this attribute uses.
805 =item B<associate_method ($method)>
807 This will associate a C<$method> with the given attribute which is
808 used internally by the accessor generator.
810 =item B<associated_methods>
812 This will return the list of methods which have been associated with
813 the C<associate_method> methods. This is a good way of seeing what
814 methods are used to manage a given attribute.
816 =item B<install_accessors>
818 This allows the attribute to generate and install code for it's own
819 I<accessor/reader/writer/predicate> methods. This is called by
820 C<Class::MOP::Class::add_attribute>.
822 This method will call C<process_accessors> for each of the possible
823 method types (accessor, reader, writer & predicate).
825 =item B<process_accessors ($type, $value)>
827 This takes a C<$type> (accessor, reader, writer or predicate), and
828 a C<$value> (the value passed into the constructor for each of the
829 different types). It will then either generate the method itself
830 (using the C<generate_*_method> methods listed below) or it will
831 use the custom method passed through the constructor.
833 =item B<remove_accessors>
835 This allows the attribute to remove the method for it's own
836 I<accessor/reader/writer/predicate/clearer>. This is called by
837 C<Class::MOP::Class::remove_attribute>.
839 NOTE: This does not currently remove methods from the list returned
840 by C<associated_methods>, that is on the TODO list.
850 This will return a B<Class::MOP::Class> instance which is related
853 It should also be noted that B<Class::MOP> will actually bootstrap
854 this module by installing a number of attribute meta-objects into
855 it's metaclass. This will allow this class to reap all the benefits
856 of the MOP when subclassing it.
862 Stevan Little E<lt>stevan@iinteractive.comE<gt>
864 =head1 COPYRIGHT AND LICENSE
866 Copyright 2006-2008 by Infinity Interactive, Inc.
868 L<http://www.iinteractive.com>
870 This library is free software; you can redistribute it and/or modify
871 it under the same terms as Perl itself.