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? :)
27 my ( $class, @args ) = @_;
29 unshift @args, "name" if @args % 2 == 1;
32 my $name = $options{name};
34 (defined $name && $name)
35 || confess "You must provide a name for the attribute";
37 $options{init_arg} = $name
38 if not exists $options{init_arg};
39 if(exists $options{builder}){
40 confess("builder must be a defined scalar value which is a method name")
41 if ref $options{builder} || !(defined $options{builder});
42 confess("Setting both default and builder is not allowed.")
43 if exists $options{default};
45 (is_default_a_coderef(\%options))
46 || confess("References are not allowed as default values, you must ".
47 "wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])")
48 if exists $options{default} && ref $options{default};
50 if( $options{required} and not( defined($options{builder}) || defined($options{init_arg}) || exists $options{default} ) ) {
51 confess("A required attribute must have either 'init_arg', 'builder', or 'default'");
56 'accessor' => $options{accessor},
57 'reader' => $options{reader},
58 'writer' => $options{writer},
59 'predicate' => $options{predicate},
60 'clearer' => $options{clearer},
61 'builder' => $options{builder},
62 'init_arg' => $options{init_arg},
63 'default' => $options{default},
64 'initializer' => $options{initializer},
65 # keep a weakened link to the
66 # class we are associated with
67 'associated_class' => undef,
68 # and a list of the methods
69 # associated with this attr
70 'associated_methods' => [],
75 # this is a primative (and kludgy) clone operation
76 # for now, it will be replaced in the Class::MOP
77 # bootstrap with a proper one, however we know
78 # that this one will work fine for now.
83 || confess "Can only clone an instance";
84 return bless { %{$self}, %options } => blessed($self);
87 sub initialize_instance_slot {
88 my ($self, $meta_instance, $instance, $params) = @_;
89 my $init_arg = $self->{'init_arg'};
91 # try to fetch the init arg from the %params ...
93 # if nothing was in the %params, we can use the
94 # attribute's default value (if it has one)
95 if(defined $init_arg and exists $params->{$init_arg}){
96 $self->_set_initial_slot_value(
102 elsif (defined $self->{'default'}) {
103 $self->_set_initial_slot_value(
106 $self->default($instance),
109 elsif (defined( my $builder = $self->{'builder'})) {
110 if ($builder = $instance->can($builder)) {
111 $self->_set_initial_slot_value(
118 confess(blessed($instance)." does not support builder method '". $self->{'builder'} ."' for attribute '" . $self->name . "'");
123 sub _set_initial_slot_value {
124 my ($self, $meta_instance, $instance, $value) = @_;
126 my $slot_name = $self->name;
128 return $meta_instance->set_slot_value($instance, $slot_name, $value)
129 unless $self->has_initializer;
132 $meta_instance->set_slot_value($instance, $slot_name, $_[0]);
135 my $initializer = $self->initializer;
137 # most things will just want to set a value, so make it first arg
138 $instance->$initializer($value, $callback, $self);
142 # the next bunch of methods will get bootstrapped
143 # away in the Class::MOP bootstrapping section
145 sub name { $_[0]->{'name'} }
147 sub associated_class { $_[0]->{'associated_class'} }
148 sub associated_methods { $_[0]->{'associated_methods'} }
150 sub has_accessor { defined($_[0]->{'accessor'}) ? 1 : 0 }
151 sub has_reader { defined($_[0]->{'reader'}) ? 1 : 0 }
152 sub has_writer { defined($_[0]->{'writer'}) ? 1 : 0 }
153 sub has_predicate { defined($_[0]->{'predicate'}) ? 1 : 0 }
154 sub has_clearer { defined($_[0]->{'clearer'}) ? 1 : 0 }
155 sub has_builder { defined($_[0]->{'builder'}) ? 1 : 0 }
156 sub has_init_arg { defined($_[0]->{'init_arg'}) ? 1 : 0 }
157 sub has_default { defined($_[0]->{'default'}) ? 1 : 0 }
158 sub has_initializer { defined($_[0]->{'initializer'}) ? 1 : 0 }
160 sub accessor { $_[0]->{'accessor'} }
161 sub reader { $_[0]->{'reader'} }
162 sub writer { $_[0]->{'writer'} }
163 sub predicate { $_[0]->{'predicate'} }
164 sub clearer { $_[0]->{'clearer'} }
165 sub builder { $_[0]->{'builder'} }
166 sub init_arg { $_[0]->{'init_arg'} }
167 sub initializer { $_[0]->{'initializer'} }
169 # end bootstrapped away method section.
170 # (all methods below here are kept intact)
172 sub has_read_method { $_[0]->has_reader || $_[0]->has_accessor }
173 sub has_write_method { $_[0]->has_writer || $_[0]->has_accessor }
175 sub get_read_method {
177 my $reader = $self->reader || $self->accessor;
179 return $reader unless ref $reader;
181 my ($name) = %$reader;
185 sub get_write_method {
187 my $writer = $self->writer || $self->accessor;
189 return $writer unless ref $writer;
191 my ($name) = %$writer;
195 sub get_read_method_ref {
197 if ((my $reader = $self->get_read_method) && $self->associated_class) {
198 return $self->associated_class->get_method($reader);
201 my $code = sub { $self->get_value(@_) };
202 if (my $class = $self->associated_class) {
203 return $class->method_metaclass->wrap(
205 package_name => $class->name,
215 sub get_write_method_ref {
217 if ((my $writer = $self->get_write_method) && $self->associated_class) {
218 return $self->associated_class->get_method($writer);
221 my $code = sub { $self->set_value(@_) };
222 if (my $class = $self->associated_class) {
223 return $class->method_metaclass->wrap(
225 package_name => $class->name,
235 sub is_default_a_coderef {
236 ('CODE' eq ref($_[0]->{'default'} || $_[0]->{default}))
240 my ($self, $instance) = @_;
241 if (defined $instance && $self->is_default_a_coderef) {
242 # if the default is a CODE ref, then
243 # we pass in the instance and default
244 # can return a value based on that
245 # instance. Somewhat crude, but works.
246 return $self->{'default'}->($instance);
253 sub slots { (shift)->name }
257 sub attach_to_class {
258 my ($self, $class) = @_;
259 (blessed($class) && $class->isa('Class::MOP::Class'))
260 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
261 weaken($self->{'associated_class'} = $class);
264 sub detach_from_class {
266 $self->{'associated_class'} = undef;
271 sub associate_method {
272 my ($self, $method) = @_;
273 push @{$self->{'associated_methods'}} => $method;
278 sub set_initial_value {
279 my ($self, $instance, $value) = @_;
280 $self->_set_initial_slot_value(
281 Class::MOP::Class->initialize(blessed($instance))->get_meta_instance,
288 my ($self, $instance, $value) = @_;
290 Class::MOP::Class->initialize(blessed($instance))
292 ->set_slot_value($instance, $self->name, $value);
296 my ($self, $instance) = @_;
298 Class::MOP::Class->initialize(blessed($instance))
300 ->get_slot_value($instance, $self->name);
304 my ($self, $instance) = @_;
306 Class::MOP::Class->initialize(blessed($instance))
308 ->is_slot_initialized($instance, $self->name);
312 my ($self, $instance) = @_;
314 Class::MOP::Class->initialize(blessed($instance))
316 ->deinitialize_slot($instance, $self->name);
321 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
323 sub process_accessors {
324 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
325 if (ref($accessor)) {
326 (ref($accessor) eq 'HASH')
327 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
328 my ($name, $method) = %{$accessor};
329 $method = $self->accessor_metaclass->wrap(
331 package_name => $self->associated_class->name,
334 $self->associate_method($method);
335 return ($name, $method);
338 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
341 $method = $self->accessor_metaclass->new(
343 is_inline => $inline_me,
344 accessor_type => $type,
345 package_name => $self->associated_class->name,
349 confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
350 $self->associate_method($method);
351 return ($accessor, $method);
355 sub install_accessors {
358 my $class = $self->associated_class;
361 $self->process_accessors('accessor' => $self->accessor(), $inline)
362 ) if $self->has_accessor();
365 $self->process_accessors('reader' => $self->reader(), $inline)
366 ) if $self->has_reader();
369 $self->process_accessors('writer' => $self->writer(), $inline)
370 ) if $self->has_writer();
373 $self->process_accessors('predicate' => $self->predicate(), $inline)
374 ) if $self->has_predicate();
377 $self->process_accessors('clearer' => $self->clearer(), $inline)
378 ) if $self->has_clearer();
384 my $_remove_accessor = sub {
385 my ($accessor, $class) = @_;
386 if (ref($accessor) && ref($accessor) eq 'HASH') {
387 ($accessor) = keys %{$accessor};
389 my $method = $class->get_method($accessor);
390 $class->remove_method($accessor)
391 if (blessed($method) && $method->isa('Class::MOP::Method::Accessor'));
394 sub remove_accessors {
397 # we really need to make sure to remove from the
398 # associates methods here as well. But this is
399 # such a slimly used method, I am not worried
400 # about it right now.
401 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
402 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
403 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
404 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
405 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
419 Class::MOP::Attribute - Attribute Meta Object
423 Class::MOP::Attribute->new( foo => (
424 accessor => 'foo', # dual purpose get/set accessor
425 predicate => 'has_foo' # predicate check for defined-ness
426 init_arg => '-foo', # class->new will look for a -foo key
427 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
430 Class::MOP::Attribute->new( bar => (
431 reader => 'bar', # getter
432 writer => 'set_bar', # setter
433 predicate => 'has_bar' # predicate check for defined-ness
434 init_arg => ':bar', # class->new will look for a :bar key
435 # no default value means it is undef
440 The Attribute Protocol is almost entirely an invention of this module,
441 and is completely optional to this MOP. This is because Perl 5 does not
442 have consistent notion of what is an attribute of a class. There are
443 so many ways in which this is done, and very few (if any) are
444 easily discoverable by this module.
446 So, all that said, this module attempts to inject some order into this
447 chaos, by introducing a consistent API which can be used to create
456 =item B<new ($name, ?%options)>
458 An attribute must (at the very least), have a C<$name>. All other
459 C<%options> are contained added as key-value pairs. Acceptable keys
466 This should be a string value representing the expected key in
467 an initialization hash. For instance, if we have an I<init_arg>
468 value of C<-foo>, then the following code will Just Work.
470 MyClass->meta->construct_instance(-foo => "Hello There");
472 In an init_arg is not assigned, it will automatically use the
473 value of C<$name>. If an explicit C<undef> is given for an init_arg,
474 an attribute value can't be specified during initialization.
478 The value of this key is the name of the method that will be
479 called to obtain the value used to initialize the attribute.
480 This should be a method in the class associated with the attribute,
481 not a method in the attribute class itself.
485 The value of this key is the default value which
486 C<Class::MOP::Class::construct_instance> will initialize the
490 If the value is a simple scalar (string or number), then it can
491 be just passed as is. However, if you wish to initialize it with
492 a HASH or ARRAY ref, then you need to wrap that inside a CODE
495 Class::MOP::Attribute->new('@foo' => (
496 default => sub { [] },
501 Class::MOP::Attribute->new('%foo' => (
502 default => sub { {} },
505 If you wish to initialize an attribute with a CODE reference
506 itself, then you need to wrap that in a subroutine as well, like
509 Class::MOP::Attribute->new('&foo' => (
510 default => sub { sub { print "Hello World" } },
513 And lastly, if the value of your attribute is dependent upon
514 some other aspect of the instance structure, then you can take
515 advantage of the fact that when the I<default> value is a CODE
516 reference, it is passed the (as yet unfinished) instance structure
517 as it's only argument. So you can do things like this:
519 Class::MOP::Attribute->new('$object_identity' => (
520 default => sub { Scalar::Util::refaddr($_[0]) },
523 This last feature is fairly limited as there is no gurantee of
524 the order of attribute initializations, so you cannot perform
525 any kind of dependent initializations. However, if this is
526 something you need, you could subclass B<Class::MOP::Class> and
527 this class to acheive it. However, this is currently left as
528 an exercise to the reader :).
532 This may be a method name (referring to a method on the class with this
533 attribute) or a CODE ref. The initializer is used to set the attribute value
534 on an instance when the attribute is set during instance initialization. When
535 called, it is passed the instance (as the invocant), the value to set, a
536 slot-setting CODE ref, and the attribute meta-instance. The slot-setting code
537 is provided to make it easy to set the (possibly altered) value on the instance
538 without going through several more method calls.
540 This contrived example shows an initializer that sets the attribute to twice
543 Class::MOP::Attribute->new('$doubled' => (
545 my ($instance, $value, $set) = @_;
550 As method names can be given as initializers, one can easily make
551 attribute initialization use the writer:
553 Class::MOP::Attribute->new('$some_attr' => (
554 writer => 'some_attr',
555 initializer => 'some_attr',
558 Your writer will simply need to examine it's C<@_> and determine under
559 which context it is being called.
563 The I<accessor>, I<reader>, I<writer>, I<predicate> and I<clearer> keys can
564 contain either; the name of the method and an appropriate default one will be
565 generated for you, B<or> a HASH ref containing exactly one key (which will be
566 used as the name of the method) and one value, which should contain a CODE
567 reference which will be installed as the method itself.
573 The I<accessor> is a standard perl-style read/write accessor. It will
574 return the value of the attribute, and if a value is passed as an argument,
575 it will assign that value to the attribute.
578 This method will properly handle the following code, by assigning an
579 C<undef> value to the attribute.
581 $object->set_something(undef);
585 This is a basic read-only accessor, it will just return the value of
590 This is a basic write accessor, it accepts a single argument, and
591 assigns that value to the attribute. This method does not intentially
592 return a value, however perl will return the result of the last
593 expression in the subroutine, which returns in this returning the
594 same value that it was passed.
597 This method will properly handle the following code, by assigning an
598 C<undef> value to the attribute.
600 $object->set_something();
604 This is a basic test to see if any value has been set for the
605 attribute. It will return true (C<1>) if the attribute has been set
606 to any value (even C<undef>), and false (C<0>) otherwise.
609 The predicate will return true even when you set an attribute's
610 value to C<undef>. This behaviour has changed as of version 0.43. In
611 older versions, the predicate (erroneously) checked for attribute
612 value definedness, instead of presence as it is now.
614 If you really want to get rid of the value, you have to define and
615 use a I<clearer> (see below).
619 This is the a method that will uninitialize the attr, reverting lazy values
620 back to their "unfulfilled" state.
624 =item B<clone (%options)>
626 This will return a clone of the attribute instance, allowing the overriding
627 of various attributes through the C<%options> supplied.
629 =item B<initialize_instance_slot ($instance, $params)>
631 This method is used internally to initialize the approriate slot for this
632 attribute in a given C<$instance>, the C<$params> passed are those that were
633 passed to the constructor.
637 =head2 Value management
639 These methods are basically "backdoors" to the instance, which can be used
640 to bypass the regular accessors, but still stay within the context of the MOP.
642 These methods are not for general use, and should only be used if you really
643 know what you are doing.
647 =item B<set_value ($instance, $value)>
649 Set the value without going through the accessor. Note that this may be done to
650 even attributes with just read only accessors.
652 =item B<set_initial_value ($instance, $value)>
654 This method sets the value without going through the accessor -- but it is only
655 called when the instance data is first initialized.
657 =item B<get_value ($instance)>
659 Return the value without going through the accessor. Note that this may be done
660 even to attributes with just write only accessors.
662 =item B<has_value ($instance)>
664 Return a boolean indicating if the item in the C<$instance> has a value in it.
665 This is basically what the default C<predicate> method calls.
667 =item B<clear_value ($instance)>
669 This will clear the value in the C<$instance>. This is basically what the default
670 C<clearer> would call. Note that this may be done even if the attirbute does not
671 have any associated read, write or clear methods.
677 These are all basic read-only value accessors for the values
678 passed into C<new>. I think they are pretty much self-explanitory.
698 =item B<is_default_a_coderef>
700 =item B<default (?$instance)>
702 Return the default value for the attribute.
704 If you pass in an C<$instance> argument to this accessor and the
705 I<default> is a CODE reference, then the CODE reference will be
706 executed with the C<$instance> as its argument.
710 Return a list of slots required by the attribute. This is usually
711 just one, which is the name of the attribute.
713 =item B<get_read_method>
715 =item B<get_write_method>
717 Return the name of a method name suitable for reading / writing the value
718 of the attribute in the associated class. Suitable for use whether
719 C<reader> and C<writer> or C<accessor> was used.
721 =item B<get_read_method_ref>
723 =item B<get_write_method_ref>
725 Return the CODE reference of a method suitable for reading / writing the
726 value of the attribute in the associated class. Suitable for use whether
727 C<reader> and C<writer> or C<accessor> was specified or not.
729 NOTE: If no reader/writer/accessor was specified, this will use the
730 attribute get_value/set_value methods, which can be very inefficient.
732 =item B<has_read_method>
734 =item B<has_write_method>
736 Return whether a method exists suitable for reading / writing the value
737 of the attribute in the associated class. Suitable for use whether
738 C<reader> and C<writer> or C<accessor> was used.
742 =head2 Informational predicates
744 These are all basic predicate methods for the values passed into C<new>.
748 =item B<has_accessor>
754 =item B<has_predicate>
758 =item B<has_initializer>
760 =item B<has_init_arg>
768 =head2 Class association
770 These methods allow you to manage the attributes association with
771 the class that contains it. These methods should not be used
772 lightly, nor are they very magical, they are mostly used internally
773 and by metaclass instances.
777 =item B<associated_class>
779 This returns the metaclass this attribute is associated with.
781 =item B<attach_to_class ($class)>
783 This will store a weaken reference to C<$class> internally. You should
784 note that just changing the class assocation will not remove the attribute
785 from it's old class, and initialize it (and it's accessors) in the new
786 C<$class>. It is up to you to do this manually.
788 =item B<detach_from_class>
790 This will remove the weakened reference to the class. It does B<not>
791 remove the attribute itself from the class (or remove it's accessors),
792 you must do that yourself if you want too. Actually if that is what
793 you want to do, you should probably be looking at
794 L<Class::MOP::Class::remove_attribute> instead.
798 =head2 Attribute Accessor generation
802 =item B<accessor_metaclass>
804 Accessors are generated by an accessor metaclass, which is usually
805 a subclass of C<Class::MOP::Method::Accessor>. This method returns
806 the name of the accessor metaclass that this attribute uses.
808 =item B<associate_method ($method)>
810 This will associate a C<$method> with the given attribute which is
811 used internally by the accessor generator.
813 =item B<associated_methods>
815 This will return the list of methods which have been associated with
816 the C<associate_method> methods. This is a good way of seeing what
817 methods are used to manage a given attribute.
819 =item B<install_accessors>
821 This allows the attribute to generate and install code for it's own
822 I<accessor/reader/writer/predicate> methods. This is called by
823 C<Class::MOP::Class::add_attribute>.
825 This method will call C<process_accessors> for each of the possible
826 method types (accessor, reader, writer & predicate).
828 =item B<process_accessors ($type, $value)>
830 This takes a C<$type> (accessor, reader, writer or predicate), and
831 a C<$value> (the value passed into the constructor for each of the
832 different types). It will then either generate the method itself
833 (using the C<generate_*_method> methods listed below) or it will
834 use the custom method passed through the constructor.
836 =item B<remove_accessors>
838 This allows the attribute to remove the method for it's own
839 I<accessor/reader/writer/predicate/clearer>. This is called by
840 C<Class::MOP::Class::remove_attribute>.
842 NOTE: This does not currently remove methods from the list returned
843 by C<associated_methods>, that is on the TODO list.
853 This will return a B<Class::MOP::Class> instance which is related
856 It should also be noted that B<Class::MOP> will actually bootstrap
857 this module by installing a number of attribute meta-objects into
858 it's metaclass. This will allow this class to reap all the benefits
859 of the MOP when subclassing it.
865 Stevan Little E<lt>stevan@iinteractive.comE<gt>
867 =head1 COPYRIGHT AND LICENSE
869 Copyright 2006-2008 by Infinity Interactive, Inc.
871 L<http://www.iinteractive.com>
873 This library is free software; you can redistribute it and/or modify
874 it under the same terms as Perl itself.