2 package Class::MOP::Attribute;
7 use Class::MOP::Method::Accessor;
10 use Scalar::Util 'blessed', 'reftype', 'weaken';
12 our $VERSION = '0.23';
13 our $AUTHORITY = 'cpan:STEVAN';
15 use base 'Class::MOP::Object';
18 require Class::MOP::Class;
19 Class::MOP::Class->initialize(blessed($_[0]) || $_[0]);
22 # NOTE: (meta-circularity)
23 # This method will be replaced in the
24 # boostrap section of Class::MOP, by
25 # a new version which uses the
26 # &Class::MOP::Class::construct_instance
27 # method to build an attribute meta-object
28 # which itself is described with attribute
30 # - Ain't meta-circularity grand? :)
36 (defined $name && $name)
37 || confess "You must provide a name for the attribute";
39 $options{init_arg} = $name
40 if not exists $options{init_arg};
41 if(exists $options{builder}){
42 confess("builder must be a defined scalar value which is a method name")
43 if ref $options{builder} || !(defined $options{builder});
44 confess("Setting both default and builder is not allowed.")
45 if exists $options{default};
47 (is_default_a_coderef(\%options))
48 || confess("References are not allowed as default values, you must ".
49 "wrap then in a CODE reference (ex: sub { [] } and not [])")
50 if exists $options{default} && ref $options{default};
52 if( $options{required} and not( defined($options{builder}) || defined($options{init_arg}) || exists $options{default} ) ) {
53 confess("A required attribute must have either 'init_arg', 'builder', or 'default'");
57 '$!accessor' => $options{accessor},
58 '$!reader' => $options{reader},
59 '$!writer' => $options{writer},
60 '$!predicate' => $options{predicate},
61 '$!clearer' => $options{clearer},
62 '$!builder' => $options{builder},
63 '$!init_arg' => $options{init_arg},
64 '$!default' => $options{default},
65 '$!initializer' => $options{initializer},
66 # keep a weakened link to the
67 # class we are associated with
68 '$!associated_class' => undef,
69 # and a list of the methods
70 # associated with this attr
71 '@!associated_methods' => [],
73 # protect this from silliness
74 init_arg => '!............( DO NOT DO THIS )............!',
79 # this is a primative (and kludgy) clone operation
80 # for now, it will be replaced in the Class::MOP
81 # bootstrap with a proper one, however we know
82 # that this one will work fine for now.
87 || confess "Can only clone an instance";
88 return bless { %{$self}, %options } => blessed($self);
91 sub initialize_instance_slot {
92 my ($self, $meta_instance, $instance, $params) = @_;
93 my $init_arg = $self->{'$!init_arg'};
94 # try to fetch the init arg from the %params ...
96 # if nothing was in the %params, we can use the
97 # attribute's default value (if it has one)
98 if(defined $init_arg and exists $params->{$init_arg}){
99 $self->_set_initial_slot_value(
102 $params->{$init_arg},
105 elsif (defined $self->{'$!default'}) {
106 $self->_set_initial_slot_value(
109 $self->default($instance),
112 elsif (defined( my $builder = $self->{'$!builder'})) {
113 if ($builder = $instance->can($builder)) {
114 $self->_set_initial_slot_value(
121 confess(blessed($instance)." does not support builder method '". $self->{'$!builder'} ."' for attribute '" . $self->name . "'");
126 sub _set_initial_slot_value {
127 my ($self, $meta_instance, $instance, $value) = @_;
129 my $slot_name = $self->name;
131 return $meta_instance->set_slot_value($instance, $slot_name, $value)
132 unless $self->has_initializer;
135 $meta_instance->set_slot_value($instance, $slot_name, $_[0]);
138 my $initializer = $self->initializer;
140 # most things will just want to set a value, so make it first arg
141 $instance->$initializer($value, $callback, $self);
145 # the next bunch of methods will get bootstrapped
146 # away in the Class::MOP bootstrapping section
148 sub name { $_[0]->{'$!name'} }
150 sub associated_class { $_[0]->{'$!associated_class'} }
151 sub associated_methods { $_[0]->{'@!associated_methods'} }
153 sub has_accessor { defined($_[0]->{'$!accessor'}) ? 1 : 0 }
154 sub has_reader { defined($_[0]->{'$!reader'}) ? 1 : 0 }
155 sub has_writer { defined($_[0]->{'$!writer'}) ? 1 : 0 }
156 sub has_predicate { defined($_[0]->{'$!predicate'}) ? 1 : 0 }
157 sub has_clearer { defined($_[0]->{'$!clearer'}) ? 1 : 0 }
158 sub has_builder { defined($_[0]->{'$!builder'}) ? 1 : 0 }
159 sub has_init_arg { defined($_[0]->{'$!init_arg'}) ? 1 : 0 }
160 sub has_default { defined($_[0]->{'$!default'}) ? 1 : 0 }
161 sub has_initializer { defined($_[0]->{'$!initializer'}) ? 1 : 0 }
163 sub accessor { $_[0]->{'$!accessor'} }
164 sub reader { $_[0]->{'$!reader'} }
165 sub writer { $_[0]->{'$!writer'} }
166 sub predicate { $_[0]->{'$!predicate'} }
167 sub clearer { $_[0]->{'$!clearer'} }
168 sub builder { $_[0]->{'$!builder'} }
169 sub init_arg { $_[0]->{'$!init_arg'} }
170 sub initializer { $_[0]->{'$!initializer'} }
172 # end bootstrapped away method section.
173 # (all methods below here are kept intact)
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 return sub { $self->get_value(@_) };
205 sub get_write_method_ref {
207 if ((my $writer = $self->get_write_method) && $self->associated_class) {
208 return $self->associated_class->get_method($writer);
211 return sub { $self->set_value(@_) };
215 sub is_default_a_coderef {
216 ('CODE' eq (reftype($_[0]->{'$!default'} || $_[0]->{default}) || ''))
220 my ($self, $instance) = @_;
221 if (defined $instance && $self->is_default_a_coderef) {
222 # if the default is a CODE ref, then
223 # we pass in the instance and default
224 # can return a value based on that
225 # instance. Somewhat crude, but works.
226 return $self->{'$!default'}->($instance);
228 $self->{'$!default'};
233 sub slots { (shift)->name }
237 sub attach_to_class {
238 my ($self, $class) = @_;
239 (blessed($class) && $class->isa('Class::MOP::Class'))
240 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
241 weaken($self->{'$!associated_class'} = $class);
244 sub detach_from_class {
246 $self->{'$!associated_class'} = undef;
251 sub associate_method {
252 my ($self, $method) = @_;
253 push @{$self->{'@!associated_methods'}} => $method;
258 sub set_initial_value {
259 my ($self, $instance, $value) = @_;
260 $self->set_initial_slot_value(
261 Class::MOP::Class->initialize(blessed($instance))->get_meta_instance,
268 my ($self, $instance, $value) = @_;
270 Class::MOP::Class->initialize(blessed($instance))
272 ->set_slot_value($instance, $self->name, $value);
276 my ($self, $instance) = @_;
278 Class::MOP::Class->initialize(blessed($instance))
280 ->get_slot_value($instance, $self->name);
284 my ($self, $instance) = @_;
286 Class::MOP::Class->initialize(blessed($instance))
288 ->is_slot_initialized($instance, $self->name);
292 my ($self, $instance) = @_;
294 Class::MOP::Class->initialize(blessed($instance))
296 ->deinitialize_slot($instance, $self->name);
301 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
303 sub process_accessors {
304 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
305 if (reftype($accessor)) {
306 (reftype($accessor) eq 'HASH')
307 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
308 my ($name, $method) = %{$accessor};
309 $method = $self->accessor_metaclass->wrap($method);
310 $self->associate_method($method);
311 return ($name, $method);
314 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
317 $method = $self->accessor_metaclass->new(
319 is_inline => $inline_me,
320 accessor_type => $type,
323 confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
324 $self->associate_method($method);
325 return ($accessor, $method);
329 sub install_accessors {
332 my $class = $self->associated_class;
335 $self->process_accessors('accessor' => $self->accessor(), $inline)
336 ) if $self->has_accessor();
339 $self->process_accessors('reader' => $self->reader(), $inline)
340 ) if $self->has_reader();
343 $self->process_accessors('writer' => $self->writer(), $inline)
344 ) if $self->has_writer();
347 $self->process_accessors('predicate' => $self->predicate(), $inline)
348 ) if $self->has_predicate();
351 $self->process_accessors('clearer' => $self->clearer(), $inline)
352 ) if $self->has_clearer();
358 my $_remove_accessor = sub {
359 my ($accessor, $class) = @_;
360 if (reftype($accessor) && reftype($accessor) eq 'HASH') {
361 ($accessor) = keys %{$accessor};
363 my $method = $class->get_method($accessor);
364 $class->remove_method($accessor)
365 if (blessed($method) && $method->isa('Class::MOP::Method::Accessor'));
368 sub remove_accessors {
371 # we really need to make sure to remove from the
372 # associates methods here as well. But this is
373 # such a slimly used method, I am not worried
374 # about it right now.
375 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
376 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
377 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
378 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
379 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
393 Class::MOP::Attribute - Attribute Meta Object
397 Class::MOP::Attribute->new('$foo' => (
398 accessor => 'foo', # dual purpose get/set accessor
399 predicate => 'has_foo' # predicate check for defined-ness
400 init_arg => '-foo', # class->new will look for a -foo key
401 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
404 Class::MOP::Attribute->new('$.bar' => (
405 reader => 'bar', # getter
406 writer => 'set_bar', # setter
407 predicate => 'has_bar' # predicate check for defined-ness
408 init_arg => ':bar', # class->new will look for a :bar key
409 # no default value means it is undef
414 The Attribute Protocol is almost entirely an invention of this module,
415 and is completely optional to this MOP. This is because Perl 5 does not
416 have consistent notion of what is an attribute of a class. There are
417 so many ways in which this is done, and very few (if any) are
418 easily discoverable by this module.
420 So, all that said, this module attempts to inject some order into this
421 chaos, by introducing a consistent API which can be used to create
430 =item B<new ($name, ?%options)>
432 An attribute must (at the very least), have a C<$name>. All other
433 C<%options> are contained added as key-value pairs. Acceptable keys
440 This should be a string value representing the expected key in
441 an initialization hash. For instance, if we have an I<init_arg>
442 value of C<-foo>, then the following code will Just Work.
444 MyClass->meta->construct_instance(-foo => "Hello There");
446 In an init_arg is not assigned, it will automatically use the
451 The value of this key is the name of the method that will be
452 called to obtain the value used to initialize the attribute.
453 This should be a method in the class associated with the attribute,
454 not a method in the attribute class itself.
458 The value of this key is the default value which
459 C<Class::MOP::Class::construct_instance> will initialize the
463 If the value is a simple scalar (string or number), then it can
464 be just passed as is. However, if you wish to initialize it with
465 a HASH or ARRAY ref, then you need to wrap that inside a CODE
468 Class::MOP::Attribute->new('@foo' => (
469 default => sub { [] },
474 Class::MOP::Attribute->new('%foo' => (
475 default => sub { {} },
478 If you wish to initialize an attribute with a CODE reference
479 itself, then you need to wrap that in a subroutine as well, like
482 Class::MOP::Attribute->new('&foo' => (
483 default => sub { sub { print "Hello World" } },
486 And lastly, if the value of your attribute is dependent upon
487 some other aspect of the instance structure, then you can take
488 advantage of the fact that when the I<default> value is a CODE
489 reference, it is passed the raw (unblessed) instance structure
490 as it's only argument. So you can do things like this:
492 Class::MOP::Attribute->new('$object_identity' => (
493 default => sub { Scalar::Util::refaddr($_[0]) },
496 This last feature is fairly limited as there is no gurantee of
497 the order of attribute initializations, so you cannot perform
498 any kind of dependent initializations. However, if this is
499 something you need, you could subclass B<Class::MOP::Class> and
500 this class to acheive it. However, this is currently left as
501 an exercise to the reader :).
505 The I<accessor>, I<reader>, I<writer>, I<predicate> and I<clearer> keys can
506 contain either; the name of the method and an appropriate default one will be
507 generated for you, B<or> a HASH ref containing exactly one key (which will be
508 used as the name of the method) and one value, which should contain a CODE
509 reference which will be installed as the method itself.
515 The I<accessor> is a standard perl-style read/write accessor. It will
516 return the value of the attribute, and if a value is passed as an argument,
517 it will assign that value to the attribute.
520 This method will properly handle the following code, by assigning an
521 C<undef> value to the attribute.
523 $object->set_something(undef);
527 This is a basic read-only accessor, it will just return the value of
532 This is a basic write accessor, it accepts a single argument, and
533 assigns that value to the attribute. This method does not intentially
534 return a value, however perl will return the result of the last
535 expression in the subroutine, which returns in this returning the
536 same value that it was passed.
539 This method will properly handle the following code, by assigning an
540 C<undef> value to the attribute.
542 $object->set_something();
546 This is a basic test to see if any value has been set for the
547 attribute. It will return true (C<1>) if the attribute has been set
548 to any value (even C<undef>), and false (C<0>) otherwise.
551 The predicate will return true even when you set an attribute's
552 value to C<undef>. This behaviour has changed as of version 0.43. In
553 older versions, the predicate (erroneously) checked for attribute
554 value definedness, instead of presence as it is now.
556 If you really want to get rid of the value, you have to define and
557 use a I<clearer> (see below).
562 This is the a method that will uninitialize the attr, reverting lazy values
563 back to their "unfulfilled" state.
567 =item B<clone (%options)>
569 =item B<initialize_instance_slot ($instance, $params)>
573 =head2 Value management
575 These methods are basically "backdoors" to the instance, which can be used
576 to bypass the regular accessors, but still stay within the context of the MOP.
578 These methods are not for general use, and should only be used if you really
579 know what you are doing.
583 =item B<set_value ($instance, $value)>
585 Set the value without going through the accessor. Note that this may be done to
586 even attributes with just read only accessors.
588 =item B<set_initial_value ($instance, $value)>
590 This method sets the value without going through the accessor -- but it is only
591 called when the instance data is first initialized.
593 =item B<get_value ($instance)>
595 Return the value without going through the accessor. Note that this may be done
596 even to attributes with just write only accessors.
598 =item B<has_value ($instance)>
600 Return a boolean indicating if the item in the C<$instance> has a value in it.
601 This is basically what the default C<predicate> method calls.
603 =item B<clear_value ($instance)>
605 This will clear the value in the C<$instance>. This is basically what the default
606 C<clearer> would call. Note that this may be done even if the attirbute does not
607 have any associated read, write or clear methods.
613 These are all basic read-only value accessors for the values
614 passed into C<new>. I think they are pretty much self-explanitory.
634 =item B<is_default_a_coderef>
636 =item B<default (?$instance)>
638 Return the default value for the attribute.
640 If you pass in an C<$instance> argument to this accessor and the
641 I<default> is a CODE reference, then the CODE reference will be
642 executed with the C<$instance> as its argument.
646 Return a list of slots required by the attribute. This is usually
647 just one, which is the name of the attribute.
649 =item B<get_read_method>
651 =item B<get_write_method>
653 Return the name of a method name suitable for reading / writing the value
654 of the attribute in the associated class. Suitable for use whether
655 C<reader> and C<writer> or C<accessor> was used.
657 =item B<get_read_method_ref>
659 =item B<get_write_method_ref>
661 Return the CODE reference of a method suitable for reading / writing the
662 value of the attribute in the associated class. Suitable for use whether
663 C<reader> and C<writer> or C<accessor> was specified or not.
665 NOTE: If not reader/writer/accessor was specified, this will use the
666 attribute get_value/set_value methods, which can be very inefficient.
670 =head2 Informational predicates
672 These are all basic predicate methods for the values passed into C<new>.
676 =item B<has_accessor>
682 =item B<has_predicate>
686 =item B<has_initializer>
688 =item B<has_init_arg>
696 =head2 Class association
698 These methods allow you to manage the attributes association with
699 the class that contains it. These methods should not be used
700 lightly, nor are they very magical, they are mostly used internally
701 and by metaclass instances.
705 =item B<associated_class>
707 This returns the metaclass this attribute is associated with.
709 =item B<attach_to_class ($class)>
711 This will store a weaken reference to C<$class> internally. You should
712 note that just changing the class assocation will not remove the attribute
713 from it's old class, and initialize it (and it's accessors) in the new
714 C<$class>. It is up to you to do this manually.
716 =item B<detach_from_class>
718 This will remove the weakened reference to the class. It does B<not>
719 remove the attribute itself from the class (or remove it's accessors),
720 you must do that yourself if you want too. Actually if that is what
721 you want to do, you should probably be looking at
722 L<Class::MOP::Class::remove_attribute> instead.
726 =head2 Attribute Accessor generation
730 =item B<accessor_metaclass>
732 Accessors are generated by an accessor metaclass, which is usually
733 a subclass of C<Class::MOP::Method::Accessor>. This method returns
734 the name of the accessor metaclass that this attribute uses.
736 =item B<associate_method ($method)>
738 This will associate a C<$method> with the given attribute which is
739 used internally by the accessor generator.
741 =item B<associated_methods>
743 This will return the list of methods which have been associated with
744 the C<associate_method> methods.
746 =item B<install_accessors>
748 This allows the attribute to generate and install code for it's own
749 I<accessor/reader/writer/predicate> methods. This is called by
750 C<Class::MOP::Class::add_attribute>.
752 This method will call C<process_accessors> for each of the possible
753 method types (accessor, reader, writer & predicate).
755 =item B<process_accessors ($type, $value)>
757 This takes a C<$type> (accessor, reader, writer or predicate), and
758 a C<$value> (the value passed into the constructor for each of the
759 different types). It will then either generate the method itself
760 (using the C<generate_*_method> methods listed below) or it will
761 use the custom method passed through the constructor.
763 =item B<remove_accessors>
765 This allows the attribute to remove the method for it's own
766 I<accessor/reader/writer/predicate/clearer>. This is called by
767 C<Class::MOP::Class::remove_attribute>.
769 NOTE: This does not currently remove methods from the list returned
770 by C<associated_methods>, that is on the TODO list.
780 This will return a B<Class::MOP::Class> instance which is related
783 It should also be noted that B<Class::MOP> will actually bootstrap
784 this module by installing a number of attribute meta-objects into
785 it's metaclass. This will allow this class to reap all the benifits
786 of the MOP when subclassing it.
792 Stevan Little E<lt>stevan@iinteractive.comE<gt>
794 =head1 COPYRIGHT AND LICENSE
796 Copyright 2006-2008 by Infinity Interactive, Inc.
798 L<http://www.iinteractive.com>
800 This library is free software; you can redistribute it and/or modify
801 it under the same terms as Perl itself.