2 package Class::MOP::Attribute;
7 use Class::MOP::Method::Accessor;
8 use Class::MOP::Method::Reader;
9 use Class::MOP::Method::Writer;
10 use Class::MOP::Method::Predicate;
13 use Scalar::Util 'blessed', 'weaken';
15 our $VERSION = '0.94';
16 $VERSION = eval $VERSION;
17 our $AUTHORITY = 'cpan:STEVAN';
19 use base 'Class::MOP::Object';
21 # NOTE: (meta-circularity)
22 # This method will be replaced in the
23 # boostrap section of Class::MOP, by
24 # a new version which uses the
25 # &Class::MOP::Class::construct_instance
26 # method to build an attribute meta-object
27 # which itself is described with attribute
29 # - Ain't meta-circularity grand? :)
31 my ( $class, @args ) = @_;
33 unshift @args, "name" if @args % 2 == 1;
36 my $name = $options{name};
39 || confess "You must provide a name for the attribute";
41 $options{init_arg} = $name
42 if not exists $options{init_arg};
43 if(exists $options{builder}){
44 confess("builder must be a defined scalar value which is a method name")
45 if ref $options{builder} || !(defined $options{builder});
46 confess("Setting both default and builder is not allowed.")
47 if exists $options{default};
49 (is_default_a_coderef(\%options))
50 || confess("References are not allowed as default values, you must ".
51 "wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])")
52 if exists $options{default} && ref $options{default};
54 if( $options{required} and not( defined($options{builder}) || defined($options{init_arg}) || exists $options{default} ) ) {
55 confess("A required attribute must have either 'init_arg', 'builder', or 'default'");
58 $class->_new(\%options);
64 return Class::MOP::Class->initialize($class)->new_object(@_)
65 if $class ne __PACKAGE__;
67 my $options = @_ == 1 ? $_[0] : {@_};
70 'name' => $options->{name},
71 'accessor' => $options->{accessor},
72 'reader' => $options->{reader},
73 'writer' => $options->{writer},
74 'predicate' => $options->{predicate},
75 'clearer' => $options->{clearer},
76 'builder' => $options->{builder},
77 'init_arg' => $options->{init_arg},
78 'default' => $options->{default},
79 'initializer' => $options->{initializer},
80 'definition_context' => $options->{definition_context},
81 'lazy' => $options->{lazy},
82 # keep a weakened link to the
83 # class we are associated with
84 'associated_class' => undef,
85 # and a list of the methods
86 # associated with this attr
87 'associated_methods' => [],
88 # this let's us keep track of
89 # our order inside the associated
91 'insertion_order' => undef,
96 # this is a primative (and kludgy) clone operation
97 # for now, it will be replaced in the Class::MOP
98 # bootstrap with a proper one, however we know
99 # that this one will work fine for now.
104 || confess "Can only clone an instance";
105 return bless { %{$self}, %options } => ref($self);
109 my ( $self, $instance ) = @_;
111 my $builder = $self->builder();
113 return $instance->$builder()
114 if $instance->can( $self->builder );
116 $self->throw_error( blessed($instance)
117 . " does not support builder method '"
119 . "' for attribute '"
126 sub initialize_instance_slot {
127 my ($self, $meta_instance, $instance, $params) = @_;
128 my $init_arg = $self->{'init_arg'};
130 my ($val, $value_is_set);
131 # try to fetch the init arg from the %params ...
133 # if nothing was in the %params, we can use the
134 # attribute's default value (if it has one)
135 if(defined $init_arg and exists $params->{$init_arg}){
136 $val = $params->{$init_arg};
139 return if $self->is_lazy;
141 if($self->has_default){
142 $val = $self->default($instance);
144 } elsif($self->has_builder){
145 $val = $self->_call_builder($instance);
150 return unless $value_is_set;
152 $self->_set_initial_slot_value(
160 sub _set_initial_slot_value {
161 my ($self, $meta_instance, $instance, $value) = @_;
163 my $slot_name = $self->name;
165 return $meta_instance->set_slot_value($instance, $slot_name, $value)
166 unless $self->has_initializer;
169 $meta_instance->set_slot_value($instance, $slot_name, $_[0]);
172 my $initializer = $self->initializer;
174 # most things will just want to set a value, so make it first arg
175 $instance->$initializer($value, $callback, $self);
179 # the next bunch of methods will get bootstrapped
180 # away in the Class::MOP bootstrapping section
182 sub associated_class { $_[0]->{'associated_class'} }
183 sub associated_methods { $_[0]->{'associated_methods'} }
185 sub has_accessor { defined($_[0]->{'accessor'}) }
186 sub has_reader { defined($_[0]->{'reader'}) }
187 sub has_writer { defined($_[0]->{'writer'}) }
188 sub has_predicate { defined($_[0]->{'predicate'}) }
189 sub has_clearer { defined($_[0]->{'clearer'}) }
190 sub has_builder { defined($_[0]->{'builder'}) }
191 sub has_init_arg { defined($_[0]->{'init_arg'}) }
192 sub has_default { defined($_[0]->{'default'}) }
193 sub has_initializer { defined($_[0]->{'initializer'}) }
194 sub has_insertion_order { defined($_[0]->{'insertion_order'}) }
196 sub accessor { $_[0]->{'accessor'} }
197 sub reader { $_[0]->{'reader'} }
198 sub writer { $_[0]->{'writer'} }
199 sub predicate { $_[0]->{'predicate'} }
200 sub clearer { $_[0]->{'clearer'} }
201 sub builder { $_[0]->{'builder'} }
202 sub init_arg { $_[0]->{'init_arg'} }
203 sub initializer { $_[0]->{'initializer'} }
204 sub definition_context { $_[0]->{'definition_context'} }
205 sub insertion_order { $_[0]->{'insertion_order'} }
206 sub _set_insertion_order { $_[0]->{'insertion_order'} = $_[1] }
207 sub is_lazy { $_[0]->{'lazy'} }
209 # end bootstrapped away method section.
210 # (all methods below here are kept intact)
212 sub has_read_method { $_[0]->has_reader || $_[0]->has_accessor }
213 sub has_write_method { $_[0]->has_writer || $_[0]->has_accessor }
215 sub get_read_method {
217 my $reader = $self->reader || $self->accessor;
219 return $reader unless ref $reader;
221 my ($name) = %$reader;
225 sub get_write_method {
227 my $writer = $self->writer || $self->accessor;
229 return $writer unless ref $writer;
231 my ($name) = %$writer;
235 sub get_read_method_ref {
237 if ((my $reader = $self->get_read_method) && $self->associated_class) {
238 return $self->associated_class->get_method($reader);
241 my $code = sub { $self->get_value(@_) };
242 if (my $class = $self->associated_class) {
243 return $class->method_metaclass->wrap(
245 package_name => $class->name,
255 sub get_write_method_ref {
257 if ((my $writer = $self->get_write_method) && $self->associated_class) {
258 return $self->associated_class->get_method($writer);
261 my $code = sub { $self->set_value(@_) };
262 if (my $class = $self->associated_class) {
263 return $class->method_metaclass->wrap(
265 package_name => $class->name,
275 sub is_default_a_coderef {
276 my ($value) = $_[0]->{'default'};
277 return unless ref($value);
278 return ref($value) eq 'CODE' || (blessed($value) && $value->isa('Class::MOP::Method'));
282 my ($self, $instance) = @_;
283 if (defined $instance && $self->is_default_a_coderef) {
284 # if the default is a CODE ref, then
285 # we pass in the instance and default
286 # can return a value based on that
287 # instance. Somewhat crude, but works.
288 return $self->{'default'}->($instance);
295 sub slots { (shift)->name }
299 sub attach_to_class {
300 my ($self, $class) = @_;
301 (blessed($class) && $class->isa('Class::MOP::Class'))
302 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
303 weaken($self->{'associated_class'} = $class);
306 sub detach_from_class {
308 $self->{'associated_class'} = undef;
313 sub associate_method {
314 my ($self, $method) = @_;
315 push @{$self->{'associated_methods'}} => $method;
320 sub set_initial_value {
321 my ($self, $instance, $value) = @_;
322 $self->_set_initial_slot_value(
323 Class::MOP::Class->initialize(ref($instance))->get_meta_instance,
329 sub set_value { shift->set_raw_value(@_) }
330 sub get_value { shift->get_raw_value(@_) }
333 my ($self, $instance, $value) = @_;
335 Class::MOP::Class->initialize(ref($instance))
337 ->set_slot_value($instance, $self->name, $value);
341 my ($self, $instance) = @_;
343 if($self->is_lazy && !$self->has_value($instance)){
346 if($self->has_default){
347 $val = $self->default($instance);
348 } elsif($self->has_builder){
349 $val = $self->_call_builder($instance);
352 $self->set_initial_value(
358 Class::MOP::Class->initialize(ref($instance))
360 ->get_slot_value($instance, $self->name);
364 my ($self, $instance) = @_;
366 Class::MOP::Class->initialize(ref($instance))
368 ->is_slot_initialized($instance, $self->name);
372 my ($self, $instance) = @_;
374 Class::MOP::Class->initialize(ref($instance))
376 ->deinitialize_slot($instance, $self->name);
381 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
382 sub method_metaclasses {
384 reader => 'Class::MOP::Method::Reader',
385 writer => 'Class::MOP::Method::Writer',
386 predicate => 'Class::MOP::Method::Predicate',
390 sub _process_accessors {
391 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
395 if ( my $ctx = $self->definition_context ) {
396 $method_ctx = { %$ctx };
399 if (ref($accessor)) {
400 (ref($accessor) eq 'HASH')
401 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
402 my ($name, $method) = %{$accessor};
403 $method = $self->accessor_metaclass->wrap(
405 package_name => $self->associated_class->name,
407 definition_context => $method_ctx,
409 $self->associate_method($method);
410 return ($name, $method);
413 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
417 my $desc = "accessor $accessor";
418 if ( $accessor ne $self->name ) {
419 $desc .= " of attribute " . $self->name;
422 $method_ctx->{description} = $desc;
425 my $method_metaclass = $self->method_metaclasses->{$type} || $self->accessor_metaclass;
427 $method = $method_metaclass->new(
429 is_inline => $inline_me,
430 accessor_type => $type,
431 package_name => $self->associated_class->name,
433 definition_context => $method_ctx,
436 confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
437 $self->associate_method($method);
438 return ($accessor, $method);
442 sub install_accessors {
445 my $class = $self->associated_class;
448 $self->_process_accessors('accessor' => $self->accessor(), $inline)
449 ) if $self->has_accessor();
452 $self->_process_accessors('reader' => $self->reader(), $inline)
453 ) if $self->has_reader();
456 $self->_process_accessors('writer' => $self->writer(), $inline)
457 ) if $self->has_writer();
460 $self->_process_accessors('predicate' => $self->predicate(), $inline)
461 ) if $self->has_predicate();
464 $self->_process_accessors('clearer' => $self->clearer(), $inline)
465 ) if $self->has_clearer();
471 my $_remove_accessor = sub {
472 my ($accessor, $class) = @_;
473 if (ref($accessor) && ref($accessor) eq 'HASH') {
474 ($accessor) = keys %{$accessor};
476 my $method = $class->get_method($accessor);
477 $class->remove_method($accessor)
478 if (ref($method) && $method->isa('Class::MOP::Method::Attribute'));
481 sub remove_accessors {
484 # we really need to make sure to remove from the
485 # associates methods here as well. But this is
486 # such a slimly used method, I am not worried
487 # about it right now.
488 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
489 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
490 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
491 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
492 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
506 Class::MOP::Attribute - Attribute Meta Object
510 Class::MOP::Attribute->new(
512 accessor => 'foo', # dual purpose get/set accessor
513 predicate => 'has_foo', # predicate check for defined-ness
514 init_arg => '-foo', # class->new will look for a -foo key
515 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
519 Class::MOP::Attribute->new(
521 reader => 'bar', # getter
522 writer => 'set_bar', # setter
523 predicate => 'has_bar', # predicate check for defined-ness
524 init_arg => ':bar', # class->new will look for a :bar key
525 # no default value means it is undef
531 The Attribute Protocol is almost entirely an invention of
532 C<Class::MOP>. Perl 5 does not have a consistent notion of
533 attributes. There are so many ways in which this is done, and very few
534 (if any) are easily discoverable by this module.
536 With that said, this module attempts to inject some order into this
537 chaos, by introducing a consistent API which can be used to create
546 =item B<< Class::MOP::Attribute->new($name, ?%options) >>
548 An attribute must (at the very least), have a C<$name>. All other
549 C<%options> are added as key-value pairs.
555 This is a string value representing the expected key in an
556 initialization hash. For instance, if we have an C<init_arg> value of
557 C<-foo>, then the following code will Just Work.
559 MyClass->meta->new_object( -foo => 'Hello There' );
561 If an init_arg is not assigned, it will automatically use the
562 attribute's name. If C<init_arg> is explicitly set to C<undef>, the
563 attribute cannot be specified during initialization.
567 This provides the name of a method that will be called to initialize
568 the attribute. This method will be called on the object after it is
569 constructed. It is expected to return a valid value for the attribute.
573 This can be used to provide an explicit default for initializing the
574 attribute. If the default you provide is a subroutine reference, then
575 this reference will be called I<as a method> on the object.
577 If the value is a simple scalar (string or number), then it can be
578 just passed as is. However, if you wish to initialize it with a HASH
579 or ARRAY ref, then you need to wrap that inside a subroutine
582 Class::MOP::Attribute->new(
584 default => sub { [] },
590 Class::MOP::Attribute->new(
592 default => sub { {} },
596 If you wish to initialize an attribute with a subroutine reference
597 itself, then you need to wrap that in a subroutine as well:
599 Class::MOP::Attribute->new(
602 sub { print "Hello World" }
607 And lastly, if the value of your attribute is dependent upon some
608 other aspect of the instance structure, then you can take advantage of
609 the fact that when the C<default> value is called as a method:
611 Class::MOP::Attribute->new(
612 'object_identity' => (
613 default => sub { Scalar::Util::refaddr( $_[0] ) },
617 Note that there is no guarantee that attributes are initialized in any
618 particular order, so you cannot rely on the value of some other
619 attribute when generating the default.
623 This option can be either a method name or a subroutine
624 reference. This method will be called when setting the attribute's
625 value in the constructor. Unlike C<default> and C<builder>, the
626 initializer is only called when a value is provided to the
627 constructor. The initializer allows you to munge this value during
630 The initializer is called as a method with three arguments. The first
631 is the value that was passed to the constructor. The second is a
632 subroutine reference that can be called to actually set the
633 attribute's value, and the last is the associated
634 C<Class::MOP::Attribute> object.
636 This contrived example shows an initializer that sets the attribute to
637 twice the given value.
639 Class::MOP::Attribute->new(
642 my ( $self, $value, $set, $attr ) = @_;
643 $set->( $value * 2 );
648 Since an initializer can be a method name, you can easily make
649 attribute initialization use the writer:
651 Class::MOP::Attribute->new(
653 writer => 'some_attr',
654 initializer => 'some_attr',
658 Your writer will need to examine C<@_> and determine under which
659 context it is being called.
663 The C<accessor>, C<reader>, C<writer>, C<predicate> and C<clearer>
664 options all accept the same parameters. You can provide the name of
665 the method, in which case an appropriate default method will be
666 generated for you. Or instead you can also provide hash reference
667 containing exactly one key (the method name) and one value. The value
668 should be a subroutine reference, which will be installed as the
675 An C<accessor> is a standard Perl-style read/write accessor. It will
676 return the value of the attribute, and if a value is passed as an
677 argument, it will assign that value to the attribute.
679 Note that C<undef> is a legitimate value, so this will work:
681 $object->set_something(undef);
685 This is a basic read-only accessor. It returns the value of the
690 This is a basic write accessor, it accepts a single argument, and
691 assigns that value to the attribute.
693 Note that C<undef> is a legitimate value, so this will work:
695 $object->set_something(undef);
699 The predicate method returns a boolean indicating whether or not the
700 attribute has been explicitly set.
702 Note that the predicate returns true even if the attribute was set to
703 a false value (C<0> or C<undef>).
707 This method will uninitialize the attribute. After an attribute is
708 cleared, its C<predicate> will return false.
710 =item * definition_context
712 Mostly, this exists as a hook for the benefit of Moose.
714 This option should be a hash reference containing several keys which
715 will be used when inlining the attribute's accessors. The keys should
716 include C<line>, the line number where the attribute was created, and
717 either C<file> or C<description>.
719 This information will ultimately be used when eval'ing inlined
720 accessor code so that error messages report a useful line and file
725 =item B<< $attr->clone(%options) >>
727 This clones the attribute. Any options you provide will override the
728 settings of the original attribute. You can change the name of the new
729 attribute by passing a C<name> key in C<%options>.
735 These are all basic read-only accessors for the values passed into
740 =item B<< $attr->name >>
742 Returns the attribute's name.
744 =item B<< $attr->accessor >>
746 =item B<< $attr->reader >>
748 =item B<< $attr->writer >>
750 =item B<< $attr->predicate >>
752 =item B<< $attr->clearer >>
754 The C<accessor>, C<reader>, C<writer>, C<predicate>, and C<clearer>
755 methods all return exactly what was passed to the constructor, so it
756 can be either a string containing a method name, or a hash reference.
758 =item B<< $attr->initializer >>
760 Returns the initializer as passed to the constructor, so this may be
761 either a method name or a subroutine reference.
763 =item B<< $attr->init_arg >>
765 =item B<< $attr->is_default_a_coderef >>
767 =item B<< $attr->default($instance) >>
769 The C<$instance> argument is optional. If you don't pass it, the
770 return value for this method is exactly what was passed to the
771 constructor, either a simple scalar or a subroutine reference.
773 If you I<do> pass an C<$instance> and the default is a subroutine
774 reference, then the reference is called as a method on the
775 C<$instance> and the generated value is returned.
777 =item B<< $attr->slots >>
779 Return a list of slots required by the attribute. This is usually just
780 one, the name of the attribute.
782 A slot is the name of the hash key used to store the attribute in an
785 =item B<< $attr->get_read_method >>
787 =item B<< $attr->get_write_method >>
789 Returns the name of a method suitable for reading or writing the value
790 of the attribute in the associated class.
792 If an attribute is read- or write-only, then these methods can return
793 C<undef> as appropriate.
795 =item B<< $attr->has_read_method >>
797 =item B<< $attr->has_write_method >>
799 This returns a boolean indicating whether the attribute has a I<named>
800 read or write method.
802 =item B<< $attr->get_read_method_ref >>
804 =item B<< $attr->get_write_method_ref >>
806 Returns the subroutine reference of a method suitable for reading or
807 writing the attribute's value in the associated class. These methods
808 always return a subroutine reference, regardless of whether or not the
809 attribute is read- or write-only.
811 =item B<< $attr->insertion_order >>
813 If this attribute has been inserted into a class, this returns a zero
814 based index regarding the order of insertion.
818 =head2 Informational predicates
820 These are all basic predicate methods for the values passed into C<new>.
824 =item B<< $attr->has_accessor >>
826 =item B<< $attr->has_reader >>
828 =item B<< $attr->has_writer >>
830 =item B<< $attr->has_predicate >>
832 =item B<< $attr->has_clearer >>
834 =item B<< $attr->has_initializer >>
836 =item B<< $attr->has_init_arg >>
838 This will be I<false> if the C<init_arg> was set to C<undef>.
840 =item B<< $attr->has_default >>
842 This will be I<false> if the C<default> was set to C<undef>, since
843 C<undef> is the default C<default> anyway.
845 =item B<< $attr->has_builder >>
847 =item B<< $attr->has_insertion_order >>
849 This will be I<false> if this attribute has not be inserted into a class
853 =head2 Value management
855 These methods are basically "back doors" to the instance, and can be
856 used to bypass the regular accessors, but still stay within the MOP.
858 These methods are not for general use, and should only be used if you
859 really know what you are doing.
863 =item B<< $attr->initialize_instance_slot($meta_instance, $instance, $params) >>
865 This method is used internally to initialize the attribute's slot in
866 the object C<$instance>.
868 The C<$params> is a hash reference of the values passed to the object
871 It's unlikely that you'll need to call this method yourself.
873 =item B<< $attr->set_value($instance, $value) >>
875 Sets the value without going through the accessor. Note that this
876 works even with read-only attributes.
878 =item B<< $attr->set_raw_value($instance, $value) >>
880 Sets the value with no side effects such as a trigger.
882 This doesn't actually apply to Class::MOP attributes, only to subclasses.
884 =item B<< $attr->set_initial_value($instance, $value) >>
886 Sets the value without going through the accessor. This method is only
887 called when the instance is first being initialized.
889 =item B<< $attr->get_value($instance) >>
891 Returns the value without going through the accessor. Note that this
892 works even with write-only accessors.
894 =item B<< $sttr->get_raw_value($instance) >>
896 Returns the value without any side effects such as lazy attributes.
898 Doesn't actually apply to Class::MOP attributes, only to subclasses.
900 =item B<< $attr->has_value($instance) >>
902 Return a boolean indicating whether the attribute has been set in
903 C<$instance>. This how the default C<predicate> method works.
905 =item B<< $attr->clear_value($instance) >>
907 This will clear the attribute's value in C<$instance>. This is what
908 the default C<clearer> calls.
910 Note that this works even if the attribute does not have any
911 associated read, write or clear methods.
915 =head2 Class association
917 These methods allow you to manage the attributes association with
918 the class that contains it. These methods should not be used
919 lightly, nor are they very magical, they are mostly used internally
920 and by metaclass instances.
924 =item B<< $attr->associated_class >>
926 This returns the C<Class::MOP::Class> with which this attribute is
929 =item B<< $attr->attach_to_class($metaclass) >>
931 This method stores a weakened reference to the C<$metaclass> object
934 This method does not remove the attribute from its old class,
935 nor does it create any accessors in the new class.
937 It is probably best to use the L<Class::MOP::Class> C<add_attribute>
940 =item B<< $attr->detach_from_class >>
942 This method removes the associate metaclass object from the attribute
945 This method does not remove the attribute itself from the class, or
946 remove its accessors.
948 It is probably best to use the L<Class::MOP::Class>
949 C<remove_attribute> method instead.
953 =head2 Attribute Accessor generation
957 =item B<< $attr->accessor_metaclass >>
959 Accessor methods are generated using an accessor metaclass. By
960 default, this is L<Class::MOP::Method::Accessor>. This method returns
961 the name of the accessor metaclass that this attribute uses.
963 =item B<< $attr->associate_method($method) >>
965 This associates a L<Class::MOP::Method> object with the
966 attribute. Typically, this is called internally when an attribute
967 generates its accessors.
969 =item B<< $attr->associated_methods >>
971 This returns the list of methods which have been associated with the
974 =item B<< $attr->install_accessors >>
976 This method generates and installs code the attributes various
977 accessors. It is typically called from the L<Class::MOP::Class>
978 C<add_attribute> method.
980 =item B<< $attr->remove_accessors >>
982 This method removes all of the accessors associated with the
985 This does not currently remove methods from the list returned by
986 C<associated_methods>.
994 =item B<< Class::MOP::Attribute->meta >>
996 This will return a L<Class::MOP::Class> instance for this class.
998 It should also be noted that L<Class::MOP> will actually bootstrap
999 this module by installing a number of attribute meta-objects into its
1006 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1008 =head1 COPYRIGHT AND LICENSE
1010 Copyright 2006-2009 by Infinity Interactive, Inc.
1012 L<http://www.iinteractive.com>
1014 This library is free software; you can redistribute it and/or modify
1015 it under the same terms as Perl itself.