2 package Class::MOP::Attribute;
7 use Class::MOP::Method::Accessor;
10 use Scalar::Util 'blessed', 'weaken';
13 our $VERSION = '1.12';
14 $VERSION = eval $VERSION;
15 our $AUTHORITY = 'cpan:STEVAN';
17 use base 'Class::MOP::Object', 'Class::MOP::Mixin::AttributeCore';
19 # NOTE: (meta-circularity)
20 # This method will be replaced in the
21 # boostrap section of Class::MOP, by
22 # a new version which uses the
23 # &Class::MOP::Class::construct_instance
24 # method to build an attribute meta-object
25 # which itself is described with attribute
27 # - Ain't meta-circularity grand? :)
29 my ( $class, @args ) = @_;
31 unshift @args, "name" if @args % 2 == 1;
34 my $name = $options{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 ($class->is_default_a_coderef(\%options))
48 || confess("References are not allowed as default values, you must ".
49 "wrap the default of '$name' 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'");
56 $class->_new(\%options);
62 return Class::MOP::Class->initialize($class)->new_object(@_)
63 if $class ne __PACKAGE__;
65 my $options = @_ == 1 ? $_[0] : {@_};
68 'name' => $options->{name},
69 'accessor' => $options->{accessor},
70 'reader' => $options->{reader},
71 'writer' => $options->{writer},
72 'predicate' => $options->{predicate},
73 'clearer' => $options->{clearer},
74 'builder' => $options->{builder},
75 'init_arg' => $options->{init_arg},
76 exists $options->{default}
77 ? ('default' => $options->{default})
79 'initializer' => $options->{initializer},
80 'definition_context' => $options->{definition_context},
81 # keep a weakened link to the
82 # class we are associated with
83 'associated_class' => undef,
84 # and a list of the methods
85 # associated with this attr
86 'associated_methods' => [],
87 # this let's us keep track of
88 # our order inside the associated
90 'insertion_order' => undef,
95 # this is a primative (and kludgy) clone operation
96 # for now, it will be replaced in the Class::MOP
97 # bootstrap with a proper one, however we know
98 # that this one will work fine for now.
103 || confess "Can only clone an instance";
104 return bless { %{$self}, %options } => ref($self);
107 sub initialize_instance_slot {
108 my ($self, $meta_instance, $instance, $params) = @_;
109 my $init_arg = $self->{'init_arg'};
111 # try to fetch the init arg from the %params ...
113 # if nothing was in the %params, we can use the
114 # attribute's default value (if it has one)
115 if(defined $init_arg and exists $params->{$init_arg}){
116 $self->_set_initial_slot_value(
119 $params->{$init_arg},
122 elsif (exists $self->{'default'}) {
123 $self->_set_initial_slot_value(
126 $self->default($instance),
129 elsif (defined( my $builder = $self->{'builder'})) {
130 if ($builder = $instance->can($builder)) {
131 $self->_set_initial_slot_value(
138 confess(ref($instance)." does not support builder method '". $self->{'builder'} ."' for attribute '" . $self->name . "'");
143 sub _set_initial_slot_value {
144 my ($self, $meta_instance, $instance, $value) = @_;
146 my $slot_name = $self->name;
148 return $meta_instance->set_slot_value($instance, $slot_name, $value)
149 unless $self->has_initializer;
151 my $callback = $self->_make_initializer_writer_callback(
152 $meta_instance, $instance, $slot_name
155 my $initializer = $self->initializer;
157 # most things will just want to set a value, so make it first arg
158 $instance->$initializer($value, $callback, $self);
161 sub _make_initializer_writer_callback {
163 my ($meta_instance, $instance, $slot_name) = @_;
166 $meta_instance->set_slot_value($instance, $slot_name, $_[0]);
170 sub get_read_method {
172 my $reader = $self->reader || $self->accessor;
174 return $reader unless ref $reader;
176 my ($name) = %$reader;
180 sub get_write_method {
182 my $writer = $self->writer || $self->accessor;
184 return $writer unless ref $writer;
186 my ($name) = %$writer;
190 sub get_read_method_ref {
192 if ((my $reader = $self->get_read_method) && $self->associated_class) {
193 return $self->associated_class->get_method($reader);
196 my $code = sub { $self->get_value(@_) };
197 if (my $class = $self->associated_class) {
198 return $class->method_metaclass->wrap(
200 package_name => $class->name,
210 sub get_write_method_ref {
212 if ((my $writer = $self->get_write_method) && $self->associated_class) {
213 return $self->associated_class->get_method($writer);
216 my $code = sub { $self->set_value(@_) };
217 if (my $class = $self->associated_class) {
218 return $class->method_metaclass->wrap(
220 package_name => $class->name,
232 sub slots { (shift)->name }
236 sub attach_to_class {
237 my ($self, $class) = @_;
238 (blessed($class) && $class->isa('Class::MOP::Class'))
239 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
240 weaken($self->{'associated_class'} = $class);
243 sub detach_from_class {
245 $self->{'associated_class'} = undef;
250 sub associate_method {
251 my ($self, $method) = @_;
252 push @{$self->{'associated_methods'}} => $method;
257 sub set_initial_value {
258 my ($self, $instance, $value) = @_;
259 $self->_set_initial_slot_value(
260 Class::MOP::Class->initialize(ref($instance))->get_meta_instance,
266 sub set_value { shift->set_raw_value(@_) }
270 my ($instance, $value) = @_;
272 my $mi = Class::MOP::Class->initialize(ref($instance))->get_meta_instance;
273 return $mi->set_slot_value($instance, $self->name, $value);
276 sub _inline_set_value {
278 return $self->_inline_instance_set(@_) . ';';
281 sub _inline_instance_set {
283 my ($instance, $value) = @_;
285 my $mi = $self->associated_class->get_meta_instance;
286 return $mi->inline_set_slot_value($instance, $self->name, $value);
289 sub get_value { shift->get_raw_value(@_) }
295 my $mi = Class::MOP::Class->initialize(ref($instance))->get_meta_instance;
296 return $mi->get_slot_value($instance, $self->name);
299 sub _inline_get_value {
301 return $self->_inline_instance_get(@_) . ';';
304 sub _inline_instance_get {
308 my $mi = $self->associated_class->get_meta_instance;
309 return $mi->inline_get_slot_value($instance, $self->name);
316 my $mi = Class::MOP::Class->initialize(ref($instance))->get_meta_instance;
317 return $mi->is_slot_initialized($instance, $self->name);
320 sub _inline_has_value {
322 return $self->_inline_instance_has(@_) . ';';
325 sub _inline_instance_has {
329 my $mi = $self->associated_class->get_meta_instance;
330 return $mi->inline_is_slot_initialized($instance, $self->name);
337 my $mi = Class::MOP::Class->initialize(ref($instance))->get_meta_instance;
338 return $mi->deinitialize_slot($instance, $self->name);
341 sub _inline_clear_value {
343 return $self->_inline_instance_clear(@_) . ';';
346 sub _inline_instance_clear {
350 my $mi = $self->associated_class->get_meta_instance;
351 return $mi->inline_deinitialize_slot($instance, $self->name);
356 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
358 sub _process_accessors {
359 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
363 if ( my $ctx = $self->definition_context ) {
364 $method_ctx = { %$ctx };
367 if (ref($accessor)) {
368 (ref($accessor) eq 'HASH')
369 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
370 my ($name, $method) = %{$accessor};
371 $method = $self->accessor_metaclass->wrap(
373 package_name => $self->associated_class->name,
375 definition_context => $method_ctx,
377 $self->associate_method($method);
378 return ($name, $method);
381 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
385 my $desc = "accessor $accessor";
386 if ( $accessor ne $self->name ) {
387 $desc .= " of attribute " . $self->name;
390 $method_ctx->{description} = $desc;
393 $method = $self->accessor_metaclass->new(
395 is_inline => $inline_me,
396 accessor_type => $type,
397 package_name => $self->associated_class->name,
399 definition_context => $method_ctx,
403 confess "Could not create the '$type' method for " . $self->name . " because : $_";
405 $self->associate_method($method);
406 return ($accessor, $method);
410 sub install_accessors {
413 my $class = $self->associated_class;
416 $self->_process_accessors('accessor' => $self->accessor(), $inline)
417 ) if $self->has_accessor();
420 $self->_process_accessors('reader' => $self->reader(), $inline)
421 ) if $self->has_reader();
424 $self->_process_accessors('writer' => $self->writer(), $inline)
425 ) if $self->has_writer();
428 $self->_process_accessors('predicate' => $self->predicate(), $inline)
429 ) if $self->has_predicate();
432 $self->_process_accessors('clearer' => $self->clearer(), $inline)
433 ) if $self->has_clearer();
439 my $_remove_accessor = sub {
440 my ($accessor, $class) = @_;
441 if (ref($accessor) && ref($accessor) eq 'HASH') {
442 ($accessor) = keys %{$accessor};
444 my $method = $class->get_method($accessor);
445 $class->remove_method($accessor)
446 if (ref($method) && $method->isa('Class::MOP::Method::Accessor'));
449 sub remove_accessors {
452 # we really need to make sure to remove from the
453 # associates methods here as well. But this is
454 # such a slimly used method, I am not worried
455 # about it right now.
456 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
457 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
458 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
459 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
460 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
474 Class::MOP::Attribute - Attribute Meta Object
478 Class::MOP::Attribute->new(
480 accessor => 'foo', # dual purpose get/set accessor
481 predicate => 'has_foo', # predicate check for defined-ness
482 init_arg => '-foo', # class->new will look for a -foo key
483 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
487 Class::MOP::Attribute->new(
489 reader => 'bar', # getter
490 writer => 'set_bar', # setter
491 predicate => 'has_bar', # predicate check for defined-ness
492 init_arg => ':bar', # class->new will look for a :bar key
493 # no default value means it is undef
499 The Attribute Protocol is almost entirely an invention of
500 C<Class::MOP>. Perl 5 does not have a consistent notion of
501 attributes. There are so many ways in which this is done, and very few
502 (if any) are easily discoverable by this module.
504 With that said, this module attempts to inject some order into this
505 chaos, by introducing a consistent API which can be used to create
514 =item B<< Class::MOP::Attribute->new($name, ?%options) >>
516 An attribute must (at the very least), have a C<$name>. All other
517 C<%options> are added as key-value pairs.
523 This is a string value representing the expected key in an
524 initialization hash. For instance, if we have an C<init_arg> value of
525 C<-foo>, then the following code will Just Work.
527 MyClass->meta->new_object( -foo => 'Hello There' );
529 If an init_arg is not assigned, it will automatically use the
530 attribute's name. If C<init_arg> is explicitly set to C<undef>, the
531 attribute cannot be specified during initialization.
535 This provides the name of a method that will be called to initialize
536 the attribute. This method will be called on the object after it is
537 constructed. It is expected to return a valid value for the attribute.
541 This can be used to provide an explicit default for initializing the
542 attribute. If the default you provide is a subroutine reference, then
543 this reference will be called I<as a method> on the object.
545 If the value is a simple scalar (string or number), then it can be
546 just passed as is. However, if you wish to initialize it with a HASH
547 or ARRAY ref, then you need to wrap that inside a subroutine
550 Class::MOP::Attribute->new(
552 default => sub { [] },
558 Class::MOP::Attribute->new(
560 default => sub { {} },
564 If you wish to initialize an attribute with a subroutine reference
565 itself, then you need to wrap that in a subroutine as well:
567 Class::MOP::Attribute->new(
570 sub { print "Hello World" }
575 And lastly, if the value of your attribute is dependent upon some
576 other aspect of the instance structure, then you can take advantage of
577 the fact that when the C<default> value is called as a method:
579 Class::MOP::Attribute->new(
580 'object_identity' => (
581 default => sub { Scalar::Util::refaddr( $_[0] ) },
585 Note that there is no guarantee that attributes are initialized in any
586 particular order, so you cannot rely on the value of some other
587 attribute when generating the default.
591 This option can be either a method name or a subroutine
592 reference. This method will be called when setting the attribute's
593 value in the constructor. Unlike C<default> and C<builder>, the
594 initializer is only called when a value is provided to the
595 constructor. The initializer allows you to munge this value during
598 The initializer is called as a method with three arguments. The first
599 is the value that was passed to the constructor. The second is a
600 subroutine reference that can be called to actually set the
601 attribute's value, and the last is the associated
602 C<Class::MOP::Attribute> object.
604 This contrived example shows an initializer that sets the attribute to
605 twice the given value.
607 Class::MOP::Attribute->new(
610 my ( $self, $value, $set, $attr ) = @_;
611 $set->( $value * 2 );
616 Since an initializer can be a method name, you can easily make
617 attribute initialization use the writer:
619 Class::MOP::Attribute->new(
621 writer => 'some_attr',
622 initializer => 'some_attr',
626 Your writer will need to examine C<@_> and determine under which
627 context it is being called.
631 The C<accessor>, C<reader>, C<writer>, C<predicate> and C<clearer>
632 options all accept the same parameters. You can provide the name of
633 the method, in which case an appropriate default method will be
634 generated for you. Or instead you can also provide hash reference
635 containing exactly one key (the method name) and one value. The value
636 should be a subroutine reference, which will be installed as the
643 An C<accessor> is a standard Perl-style read/write accessor. It will
644 return the value of the attribute, and if a value is passed as an
645 argument, it will assign that value to the attribute.
647 Note that C<undef> is a legitimate value, so this will work:
649 $object->set_something(undef);
653 This is a basic read-only accessor. It returns the value of the
658 This is a basic write accessor, it accepts a single argument, and
659 assigns that value to the attribute.
661 Note that C<undef> is a legitimate value, so this will work:
663 $object->set_something(undef);
667 The predicate method returns a boolean indicating whether or not the
668 attribute has been explicitly set.
670 Note that the predicate returns true even if the attribute was set to
671 a false value (C<0> or C<undef>).
675 This method will uninitialize the attribute. After an attribute is
676 cleared, its C<predicate> will return false.
678 =item * definition_context
680 Mostly, this exists as a hook for the benefit of Moose.
682 This option should be a hash reference containing several keys which
683 will be used when inlining the attribute's accessors. The keys should
684 include C<line>, the line number where the attribute was created, and
685 either C<file> or C<description>.
687 This information will ultimately be used when eval'ing inlined
688 accessor code so that error messages report a useful line and file
693 =item B<< $attr->clone(%options) >>
695 This clones the attribute. Any options you provide will override the
696 settings of the original attribute. You can change the name of the new
697 attribute by passing a C<name> key in C<%options>.
703 These are all basic read-only accessors for the values passed into
708 =item B<< $attr->name >>
710 Returns the attribute's name.
712 =item B<< $attr->accessor >>
714 =item B<< $attr->reader >>
716 =item B<< $attr->writer >>
718 =item B<< $attr->predicate >>
720 =item B<< $attr->clearer >>
722 The C<accessor>, C<reader>, C<writer>, C<predicate>, and C<clearer>
723 methods all return exactly what was passed to the constructor, so it
724 can be either a string containing a method name, or a hash reference.
726 =item B<< $attr->initializer >>
728 Returns the initializer as passed to the constructor, so this may be
729 either a method name or a subroutine reference.
731 =item B<< $attr->init_arg >>
733 =item B<< $attr->is_default_a_coderef >>
735 =item B<< $attr->default($instance) >>
737 The C<$instance> argument is optional. If you don't pass it, the
738 return value for this method is exactly what was passed to the
739 constructor, either a simple scalar or a subroutine reference.
741 If you I<do> pass an C<$instance> and the default is a subroutine
742 reference, then the reference is called as a method on the
743 C<$instance> and the generated value is returned.
745 =item B<< $attr->slots >>
747 Return a list of slots required by the attribute. This is usually just
748 one, the name of the attribute.
750 A slot is the name of the hash key used to store the attribute in an
753 =item B<< $attr->get_read_method >>
755 =item B<< $attr->get_write_method >>
757 Returns the name of a method suitable for reading or writing the value
758 of the attribute in the associated class.
760 If an attribute is read- or write-only, then these methods can return
761 C<undef> as appropriate.
763 =item B<< $attr->has_read_method >>
765 =item B<< $attr->has_write_method >>
767 This returns a boolean indicating whether the attribute has a I<named>
768 read or write method.
770 =item B<< $attr->get_read_method_ref >>
772 =item B<< $attr->get_write_method_ref >>
774 Returns the subroutine reference of a method suitable for reading or
775 writing the attribute's value in the associated class. These methods
776 always return a subroutine reference, regardless of whether or not the
777 attribute is read- or write-only.
779 =item B<< $attr->insertion_order >>
781 If this attribute has been inserted into a class, this returns a zero
782 based index regarding the order of insertion.
786 =head2 Informational predicates
788 These are all basic predicate methods for the values passed into C<new>.
792 =item B<< $attr->has_accessor >>
794 =item B<< $attr->has_reader >>
796 =item B<< $attr->has_writer >>
798 =item B<< $attr->has_predicate >>
800 =item B<< $attr->has_clearer >>
802 =item B<< $attr->has_initializer >>
804 =item B<< $attr->has_init_arg >>
806 This will be I<false> if the C<init_arg> was set to C<undef>.
808 =item B<< $attr->has_default >>
810 This will be I<false> if the C<default> was set to C<undef>, since
811 C<undef> is the default C<default> anyway.
813 =item B<< $attr->has_builder >>
815 =item B<< $attr->has_insertion_order >>
817 This will be I<false> if this attribute has not be inserted into a class
821 =head2 Value management
823 These methods are basically "back doors" to the instance, and can be
824 used to bypass the regular accessors, but still stay within the MOP.
826 These methods are not for general use, and should only be used if you
827 really know what you are doing.
831 =item B<< $attr->initialize_instance_slot($meta_instance, $instance, $params) >>
833 This method is used internally to initialize the attribute's slot in
834 the object C<$instance>.
836 The C<$params> is a hash reference of the values passed to the object
839 It's unlikely that you'll need to call this method yourself.
841 =item B<< $attr->set_value($instance, $value) >>
843 Sets the value without going through the accessor. Note that this
844 works even with read-only attributes.
846 =item B<< $attr->set_raw_value($instance, $value) >>
848 Sets the value with no side effects such as a trigger.
850 This doesn't actually apply to Class::MOP attributes, only to subclasses.
852 =item B<< $attr->set_initial_value($instance, $value) >>
854 Sets the value without going through the accessor. This method is only
855 called when the instance is first being initialized.
857 =item B<< $attr->get_value($instance) >>
859 Returns the value without going through the accessor. Note that this
860 works even with write-only accessors.
862 =item B<< $attr->get_raw_value($instance) >>
864 Returns the value without any side effects such as lazy attributes.
866 Doesn't actually apply to Class::MOP attributes, only to subclasses.
868 =item B<< $attr->has_value($instance) >>
870 Return a boolean indicating whether the attribute has been set in
871 C<$instance>. This how the default C<predicate> method works.
873 =item B<< $attr->clear_value($instance) >>
875 This will clear the attribute's value in C<$instance>. This is what
876 the default C<clearer> calls.
878 Note that this works even if the attribute does not have any
879 associated read, write or clear methods.
883 =head2 Class association
885 These methods allow you to manage the attributes association with
886 the class that contains it. These methods should not be used
887 lightly, nor are they very magical, they are mostly used internally
888 and by metaclass instances.
892 =item B<< $attr->associated_class >>
894 This returns the C<Class::MOP::Class> with which this attribute is
897 =item B<< $attr->attach_to_class($metaclass) >>
899 This method stores a weakened reference to the C<$metaclass> object
902 This method does not remove the attribute from its old class,
903 nor does it create any accessors in the new class.
905 It is probably best to use the L<Class::MOP::Class> C<add_attribute>
908 =item B<< $attr->detach_from_class >>
910 This method removes the associate metaclass object from the attribute
913 This method does not remove the attribute itself from the class, or
914 remove its accessors.
916 It is probably best to use the L<Class::MOP::Class>
917 C<remove_attribute> method instead.
921 =head2 Attribute Accessor generation
925 =item B<< $attr->accessor_metaclass >>
927 Accessor methods are generated using an accessor metaclass. By
928 default, this is L<Class::MOP::Method::Accessor>. This method returns
929 the name of the accessor metaclass that this attribute uses.
931 =item B<< $attr->associate_method($method) >>
933 This associates a L<Class::MOP::Method> object with the
934 attribute. Typically, this is called internally when an attribute
935 generates its accessors.
937 =item B<< $attr->associated_methods >>
939 This returns the list of methods which have been associated with the
942 =item B<< $attr->install_accessors >>
944 This method generates and installs code the attributes various
945 accessors. It is typically called from the L<Class::MOP::Class>
946 C<add_attribute> method.
948 =item B<< $attr->remove_accessors >>
950 This method removes all of the accessors associated with the
953 This does not currently remove methods from the list returned by
954 C<associated_methods>.
956 =item B<< $attr->inline_get >>
958 =item B<< $attr->inline_set >>
960 =item B<< $attr->inline_has >>
962 =item B<< $attr->inline_clear >>
964 These methods return a code snippet suitable for inlining the relevant
965 operation. They expect strings containing variable names to be used in the
966 inlining, like C<'$self'> or C<'$_[1]'>.
974 =item B<< Class::MOP::Attribute->meta >>
976 This will return a L<Class::MOP::Class> instance for this class.
978 It should also be noted that L<Class::MOP> will actually bootstrap
979 this module by installing a number of attribute meta-objects into its
986 Stevan Little E<lt>stevan@iinteractive.comE<gt>
988 =head1 COPYRIGHT AND LICENSE
990 Copyright 2006-2010 by Infinity Interactive, Inc.
992 L<http://www.iinteractive.com>
994 This library is free software; you can redistribute it and/or modify
995 it under the same terms as Perl itself.