2 package Class::MOP::Attribute;
7 use Class::MOP::Method::Accessor;
10 use Scalar::Util 'blessed', 'weaken';
12 our $VERSION = '0.89';
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 'definition_context' => $options->{definition_context},
74 # keep a weakened link to the
75 # class we are associated with
76 'associated_class' => undef,
77 # and a list of the methods
78 # associated with this attr
79 'associated_methods' => [],
80 # this let's us keep track of
81 # our order inside the associated
83 'insertion_order' => undef,
88 # this is a primative (and kludgy) clone operation
89 # for now, it will be replaced in the Class::MOP
90 # bootstrap with a proper one, however we know
91 # that this one will work fine for now.
96 || confess "Can only clone an instance";
97 return bless { %{$self}, %options } => ref($self);
100 sub initialize_instance_slot {
101 my ($self, $meta_instance, $instance, $params) = @_;
102 my $init_arg = $self->{'init_arg'};
104 # try to fetch the init arg from the %params ...
106 # if nothing was in the %params, we can use the
107 # attribute's default value (if it has one)
108 if(defined $init_arg and exists $params->{$init_arg}){
109 $self->_set_initial_slot_value(
112 $params->{$init_arg},
115 elsif (defined $self->{'default'}) {
116 $self->_set_initial_slot_value(
119 $self->default($instance),
122 elsif (defined( my $builder = $self->{'builder'})) {
123 if ($builder = $instance->can($builder)) {
124 $self->_set_initial_slot_value(
131 confess(ref($instance)." does not support builder method '". $self->{'builder'} ."' for attribute '" . $self->name . "'");
136 sub _set_initial_slot_value {
137 my ($self, $meta_instance, $instance, $value) = @_;
139 my $slot_name = $self->name;
141 return $meta_instance->set_slot_value($instance, $slot_name, $value)
142 unless $self->has_initializer;
145 $meta_instance->set_slot_value($instance, $slot_name, $_[0]);
148 my $initializer = $self->initializer;
150 # most things will just want to set a value, so make it first arg
151 $instance->$initializer($value, $callback, $self);
155 # the next bunch of methods will get bootstrapped
156 # away in the Class::MOP bootstrapping section
158 sub associated_class { $_[0]->{'associated_class'} }
159 sub associated_methods { $_[0]->{'associated_methods'} }
161 sub has_accessor { defined($_[0]->{'accessor'}) }
162 sub has_reader { defined($_[0]->{'reader'}) }
163 sub has_writer { defined($_[0]->{'writer'}) }
164 sub has_predicate { defined($_[0]->{'predicate'}) }
165 sub has_clearer { defined($_[0]->{'clearer'}) }
166 sub has_builder { defined($_[0]->{'builder'}) }
167 sub has_init_arg { defined($_[0]->{'init_arg'}) }
168 sub has_default { defined($_[0]->{'default'}) }
169 sub has_initializer { defined($_[0]->{'initializer'}) }
170 sub has_insertion_order { defined($_[0]->{'insertion_order'}) }
172 sub accessor { $_[0]->{'accessor'} }
173 sub reader { $_[0]->{'reader'} }
174 sub writer { $_[0]->{'writer'} }
175 sub predicate { $_[0]->{'predicate'} }
176 sub clearer { $_[0]->{'clearer'} }
177 sub builder { $_[0]->{'builder'} }
178 sub init_arg { $_[0]->{'init_arg'} }
179 sub initializer { $_[0]->{'initializer'} }
180 sub definition_context { $_[0]->{'definition_context'} }
181 sub insertion_order { $_[0]->{'insertion_order'} }
182 sub _set_insertion_order { $_[0]->{'insertion_order'} = $_[1] }
184 # end bootstrapped away method section.
185 # (all methods below here are kept intact)
187 sub has_read_method { $_[0]->has_reader || $_[0]->has_accessor }
188 sub has_write_method { $_[0]->has_writer || $_[0]->has_accessor }
190 sub get_read_method {
192 my $reader = $self->reader || $self->accessor;
194 return $reader unless ref $reader;
196 my ($name) = %$reader;
200 sub get_write_method {
202 my $writer = $self->writer || $self->accessor;
204 return $writer unless ref $writer;
206 my ($name) = %$writer;
210 sub get_read_method_ref {
212 if ((my $reader = $self->get_read_method) && $self->associated_class) {
213 return $self->associated_class->get_method($reader);
216 my $code = sub { $self->get_value(@_) };
217 if (my $class = $self->associated_class) {
218 return $class->method_metaclass->wrap(
220 package_name => $class->name,
230 sub get_write_method_ref {
232 if ((my $writer = $self->get_write_method) && $self->associated_class) {
233 return $self->associated_class->get_method($writer);
236 my $code = sub { $self->set_value(@_) };
237 if (my $class = $self->associated_class) {
238 return $class->method_metaclass->wrap(
240 package_name => $class->name,
250 sub is_default_a_coderef {
251 my ($value) = $_[0]->{'default'};
252 return unless ref($value);
253 return ref($value) eq 'CODE' || (blessed($value) && $value->isa('Class::MOP::Method'));
257 my ($self, $instance) = @_;
258 if (defined $instance && $self->is_default_a_coderef) {
259 # if the default is a CODE ref, then
260 # we pass in the instance and default
261 # can return a value based on that
262 # instance. Somewhat crude, but works.
263 return $self->{'default'}->($instance);
270 sub slots { (shift)->name }
274 sub attach_to_class {
275 my ($self, $class) = @_;
276 (blessed($class) && $class->isa('Class::MOP::Class'))
277 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
278 weaken($self->{'associated_class'} = $class);
281 sub detach_from_class {
283 $self->{'associated_class'} = undef;
288 sub associate_method {
289 my ($self, $method) = @_;
290 push @{$self->{'associated_methods'}} => $method;
295 sub set_initial_value {
296 my ($self, $instance, $value) = @_;
297 $self->_set_initial_slot_value(
298 Class::MOP::Class->initialize(ref($instance))->get_meta_instance,
305 my ($self, $instance, $value) = @_;
307 Class::MOP::Class->initialize(ref($instance))
309 ->set_slot_value($instance, $self->name, $value);
313 my ($self, $instance) = @_;
315 Class::MOP::Class->initialize(ref($instance))
317 ->get_slot_value($instance, $self->name);
321 my ($self, $instance) = @_;
323 Class::MOP::Class->initialize(ref($instance))
325 ->is_slot_initialized($instance, $self->name);
329 my ($self, $instance) = @_;
331 Class::MOP::Class->initialize(ref($instance))
333 ->deinitialize_slot($instance, $self->name);
338 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
340 sub process_accessors {
341 Carp::cluck('The process_accessors method has been made private.'
342 . " The public version is deprecated and will be removed in a future release.\n");
343 shift->_process_accessors(@_);
346 sub _process_accessors {
347 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
351 if ( my $ctx = $self->definition_context ) {
352 $method_ctx = { %$ctx };
355 if (ref($accessor)) {
356 (ref($accessor) eq 'HASH')
357 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
358 my ($name, $method) = %{$accessor};
359 $method = $self->accessor_metaclass->wrap(
361 package_name => $self->associated_class->name,
363 definition_context => $method_ctx,
365 $self->associate_method($method);
366 return ($name, $method);
369 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
373 my $desc = "accessor $accessor";
374 if ( $accessor ne $self->name ) {
375 $desc .= " of attribute " . $self->name;
378 $method_ctx->{description} = $desc;
381 $method = $self->accessor_metaclass->new(
383 is_inline => $inline_me,
384 accessor_type => $type,
385 package_name => $self->associated_class->name,
387 definition_context => $method_ctx,
390 confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
391 $self->associate_method($method);
392 return ($accessor, $method);
396 sub install_accessors {
399 my $class = $self->associated_class;
402 $self->_process_accessors('accessor' => $self->accessor(), $inline)
403 ) if $self->has_accessor();
406 $self->_process_accessors('reader' => $self->reader(), $inline)
407 ) if $self->has_reader();
410 $self->_process_accessors('writer' => $self->writer(), $inline)
411 ) if $self->has_writer();
414 $self->_process_accessors('predicate' => $self->predicate(), $inline)
415 ) if $self->has_predicate();
418 $self->_process_accessors('clearer' => $self->clearer(), $inline)
419 ) if $self->has_clearer();
425 my $_remove_accessor = sub {
426 my ($accessor, $class) = @_;
427 if (ref($accessor) && ref($accessor) eq 'HASH') {
428 ($accessor) = keys %{$accessor};
430 my $method = $class->get_method($accessor);
431 $class->remove_method($accessor)
432 if (ref($method) && $method->isa('Class::MOP::Method::Accessor'));
435 sub remove_accessors {
438 # we really need to make sure to remove from the
439 # associates methods here as well. But this is
440 # such a slimly used method, I am not worried
441 # about it right now.
442 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
443 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
444 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
445 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
446 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
460 Class::MOP::Attribute - Attribute Meta Object
464 Class::MOP::Attribute->new(
466 accessor => 'foo', # dual purpose get/set accessor
467 predicate => 'has_foo', # predicate check for defined-ness
468 init_arg => '-foo', # class->new will look for a -foo key
469 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
473 Class::MOP::Attribute->new(
475 reader => 'bar', # getter
476 writer => 'set_bar', # setter
477 predicate => 'has_bar', # predicate check for defined-ness
478 init_arg => ':bar', # class->new will look for a :bar key
479 # no default value means it is undef
485 The Attribute Protocol is almost entirely an invention of
486 C<Class::MOP>. Perl 5 does not have a consistent notion of
487 attributes. There are so many ways in which this is done, and very few
488 (if any) are easily discoverable by this module.
490 With that said, this module attempts to inject some order into this
491 chaos, by introducing a consistent API which can be used to create
500 =item B<< Class::MOP::Attribute->new($name, ?%options) >>
502 An attribute must (at the very least), have a C<$name>. All other
503 C<%options> are added as key-value pairs.
509 This is a string value representing the expected key in an
510 initialization hash. For instance, if we have an C<init_arg> value of
511 C<-foo>, then the following code will Just Work.
513 MyClass->meta->new_object( -foo => 'Hello There' );
515 If an init_arg is not assigned, it will automatically use the
516 attribute's name. If C<init_arg> is explicitly set to C<undef>, the
517 attribute cannot be specified during initialization.
521 This provides the name of a method that will be called to initialize
522 the attribute. This method will be called on the object after it is
523 constructed. It is expected to return a valid value for the attribute.
527 This can be used to provide an explicit default for initializing the
528 attribute. If the default you provide is a subroutine reference, then
529 this reference will be called I<as a method> on the object.
531 If the value is a simple scalar (string or number), then it can be
532 just passed as is. However, if you wish to initialize it with a HASH
533 or ARRAY ref, then you need to wrap that inside a subroutine
536 Class::MOP::Attribute->new(
538 default => sub { [] },
544 Class::MOP::Attribute->new(
546 default => sub { {} },
550 If you wish to initialize an attribute with a subroutine reference
551 itself, then you need to wrap that in a subroutine as well:
553 Class::MOP::Attribute->new(
556 sub { print "Hello World" }
561 And lastly, if the value of your attribute is dependent upon some
562 other aspect of the instance structure, then you can take advantage of
563 the fact that when the C<default> value is called as a method:
565 Class::MOP::Attribute->new(
566 'object_identity' => (
567 default => sub { Scalar::Util::refaddr( $_[0] ) },
571 Note that there is no guarantee that attributes are initialized in any
572 particular order, so you cannot rely on the value of some other
573 attribute when generating the default.
577 This option can be either a method name or a subroutine
578 reference. This method will be called when setting the attribute's
579 value in the constructor. Unlike C<default> and C<builder>, the
580 initializer is only called when a value is provided to the
581 constructor. The initializer allows you to munge this value during
584 The initializer is called as a method with three arguments. The first
585 is the value that was passed to the constructor. The second is a
586 subroutine reference that can be called to actually set the
587 attribute's value, and the last is the associated
588 C<Class::MOP::Attribute> object.
590 This contrived example shows an initializer that sets the attribute to
591 twice the given value.
593 Class::MOP::Attribute->new(
596 my ( $instance, $value, $set ) = @_;
597 $set->( $value * 2 );
602 Since an initializer can be a method name, you can easily make
603 attribute initialization use the writer:
605 Class::MOP::Attribute->new(
607 writer => 'some_attr',
608 initializer => 'some_attr',
612 Your writer will need to examine C<@_> and determine under which
613 context it is being called.
617 The C<accessor>, C<reader>, C<writer>, C<predicate> and C<clearer>
618 options all accept the same parameters. You can provide the name of
619 the method, in which case an appropriate default method will be
620 generated for you. Or instead you can also provide hash reference
621 containing exactly one key (the method name) and one value. The value
622 should be a subroutine reference, which will be installed as the
629 An C<accessor> is a standard Perl-style read/write accessor. It will
630 return the value of the attribute, and if a value is passed as an
631 argument, it will assign that value to the attribute.
633 Note that C<undef> is a legitimate value, so this will work:
635 $object->set_something(undef);
639 This is a basic read-only accessor. It returns the value of the
644 This is a basic write accessor, it accepts a single argument, and
645 assigns that value to the attribute.
647 Note that C<undef> is a legitimate value, so this will work:
649 $object->set_something(undef);
653 The predicate method returns a boolean indicating whether or not the
654 attribute has been explicitly set.
656 Note that the predicate returns true even if the attribute was set to
657 a false value (C<0> or C<undef>).
661 This method will uninitialize the attribute. After an attribute is
662 cleared, its C<predicate> will return false.
664 =item * definition_context
666 Mostly, this exists as a hook for the benefit of Moose.
668 This option should be a hash reference containing several keys which
669 will be used when inlining the attribute's accessors. The keys should
670 include C<line>, the line number where the attribute was created, and
671 either C<file> or C<description>.
673 This information will ultimately be used when eval'ing inlined
674 accessor code so that error messages report a useful line and file
679 =item B<< $attr->clone(%options) >>
681 This clones the attribute. Any options you provide will override the
682 settings of the original attribute. You can change the name of the new
683 attribute by passing a C<name> key in C<%options>.
689 These are all basic read-only accessors for the values passed into
694 =item B<< $attr->name >>
696 Returns the attribute's name.
698 =item B<< $attr->accessor >>
700 =item B<< $attr->reader >>
702 =item B<< $attr->writer >>
704 =item B<< $attr->predicate >>
706 =item B<< $attr->clearer >>
708 The C<accessor>, C<reader>, C<writer>, C<predicate>, and C<clearer>
709 methods all return exactly what was passed to the constructor, so it
710 can be either a string containing a method name, or a hash reference.
712 =item B<< $attr->initializer >>
714 Returns the initializer as passed to the constructor, so this may be
715 either a method name or a subroutine reference.
717 =item B<< $attr->init_arg >>
719 =item B<< $attr->is_default_a_coderef >>
721 =item B<< $attr->default($instance) >>
723 The C<$instance> argument is optional. If you don't pass it, the
724 return value for this method is exactly what was passed to the
725 constructor, either a simple scalar or a subroutine reference.
727 If you I<do> pass an C<$instance> and the default is a subroutine
728 reference, then the reference is called as a method on the
729 C<$instance> and the generated value is returned.
731 =item B<< $attr->slots >>
733 Return a list of slots required by the attribute. This is usually just
734 one, the name of the attribute.
736 A slot is the name of the hash key used to store the attribute in an
739 =item B<< $attr->get_read_method >>
741 =item B<< $attr->get_write_method >>
743 Returns the name of a method suitable for reading or writing the value
744 of the attribute in the associated class.
746 If an attribute is read- or write-only, then these methods can return
747 C<undef> as appropriate.
749 =item B<< $attr->has_read_method >>
751 =item B<< $attr->has_write_method >>
753 This returns a boolean indicating whether the attribute has a I<named>
754 read or write method.
756 =item B<< $attr->get_read_method_ref >>
758 =item B<< $attr->get_write_method_ref >>
760 Returns the subroutine reference of a method suitable for reading or
761 writing the attribute's value in the associated class. These methods
762 always return a subroutine reference, regardless of whether or not the
763 attribute is read- or write-only.
765 =item B<< $attr->insertion_order >>
767 If this attribute has been inserted into a class, this returns a zero
768 based index regarding the order of insertion.
772 =head2 Informational predicates
774 These are all basic predicate methods for the values passed into C<new>.
778 =item B<< $attr->has_accessor >>
780 =item B<< $attr->has_reader >>
782 =item B<< $attr->has_writer >>
784 =item B<< $attr->has_predicate >>
786 =item B<< $attr->has_clearer >>
788 =item B<< $attr->has_initializer >>
790 =item B<< $attr->has_init_arg >>
792 This will be I<false> if the C<init_arg> was set to C<undef>.
794 =item B<< $attr->has_default >>
796 This will be I<false> if the C<default> was set to C<undef>, since
797 C<undef> is the default C<default> anyway.
799 =item B<< $attr->has_builder >>
801 =item B<< $attr->has_insertion_order >>
803 This will be I<false> if this attribute has not be inserted into a class
807 =head2 Value management
809 These methods are basically "back doors" to the instance, and can be
810 used to bypass the regular accessors, but still stay within the MOP.
812 These methods are not for general use, and should only be used if you
813 really know what you are doing.
817 =item B<< $attr->initialize_instance_slot($meta_instance, $instance, $params) >>
819 This method is used internally to initialize the attribute's slot in
820 the object C<$instance>.
822 The C<$params> is a hash reference of the values passed to the object
825 It's unlikely that you'll need to call this method yourself.
827 =item B<< $attr->set_value($instance, $value) >>
829 Sets the value without going through the accessor. Note that this
830 works even with read-only attributes.
832 =item B<< $attr->set_initial_value($instance, $value) >>
834 Sets the value without going through the accessor. This method is only
835 called when the instance is first being initialized.
837 =item B<< $attr->get_value($instance) >>
839 Returns the value without going through the accessor. Note that this
840 works even with write-only accessors.
842 =item B<< $attr->has_value($instance) >>
844 Return a boolean indicating whether the attribute has been set in
845 C<$instance>. This how the default C<predicate> method works.
847 =item B<< $attr->clear_value($instance) >>
849 This will clear the attribute's value in C<$instance>. This is what
850 the default C<clearer> calls.
852 Note that this works even if the attribute does not have any
853 associated read, write or clear methods.
857 =head2 Class association
859 These methods allow you to manage the attributes association with
860 the class that contains it. These methods should not be used
861 lightly, nor are they very magical, they are mostly used internally
862 and by metaclass instances.
866 =item B<< $attr->associated_class >>
868 This returns the C<Class::MOP::Class> with which this attribute is
871 =item B<< $attr->attach_to_class($metaclass) >>
873 This method stores a weakened reference to the C<$metaclass> object
876 This method does not remove the attribute from its old class,
877 nor does it create any accessors in the new class.
879 It is probably best to use the L<Class::MOP::Class> C<add_attribute>
882 =item B<< $attr->detach_from_class >>
884 This method removes the associate metaclass object from the attribute
887 This method does not remove the attribute itself from the class, or
888 remove its accessors.
890 It is probably best to use the L<Class::MOP::Class>
891 C<remove_attribute> method instead.
895 =head2 Attribute Accessor generation
899 =item B<< $attr->accessor_metaclass >>
901 Accessor methods are generated using an accessor metaclass. By
902 default, this is L<Class::MOP::Method::Accessor>. This method returns
903 the name of the accessor metaclass that this attribute uses.
905 =item B<< $attr->associate_method($method) >>
907 This associates a L<Class::MOP::Method> object with the
908 attribute. Typically, this is called internally when an attribute
909 generates its accessors.
911 =item B<< $attr->associated_methods >>
913 This returns the list of methods which have been associated with the
916 =item B<< $attr->install_accessors >>
918 This method generates and installs code the attributes various
919 accessors. It is typically called from the L<Class::MOP::Class>
920 C<add_attribute> method.
922 =item B<< $attr->remove_accessors >>
924 This method removes all of the accessors associated with the
927 This does not currently remove methods from the list returned by
928 C<associated_methods>.
936 =item B<< Class::MOP::Attribute->meta >>
938 This will return a L<Class::MOP::Class> instance for this class.
940 It should also be noted that L<Class::MOP> will actually bootstrap
941 this module by installing a number of attribute meta-objects into its
948 Stevan Little E<lt>stevan@iinteractive.comE<gt>
950 =head1 COPYRIGHT AND LICENSE
952 Copyright 2006-2009 by Infinity Interactive, Inc.
954 L<http://www.iinteractive.com>
956 This library is free software; you can redistribute it and/or modify
957 it under the same terms as Perl itself.