2 package Class::MOP::Attribute;
8 use Scalar::Util 'blessed', 'reftype', 'weaken';
10 our $VERSION = '0.10';
13 require Class::MOP::Class;
14 Class::MOP::Class->initialize(blessed($_[0]) || $_[0]);
17 # NOTE: (meta-circularity)
18 # This method will be replaced in the
19 # boostrap section of Class::MOP, by
20 # a new version which uses the
21 # &Class::MOP::Class::construct_instance
22 # method to build an attribute meta-object
23 # which itself is described with attribute
25 # - Ain't meta-circularity grand? :)
31 (defined $name && $name)
32 || confess "You must provide a name for the attribute";
33 $options{init_arg} = $name
34 if not exists $options{init_arg};
38 accessor => $options{accessor},
39 reader => $options{reader},
40 writer => $options{writer},
41 predicate => $options{predicate},
42 clearer => $options{clearer},
43 init_arg => $options{init_arg},
44 default => $options{default},
45 # keep a weakened link to the
46 # class we are associated with
47 associated_class => undef,
52 # this is a primative (and kludgy) clone operation
53 # for now, it will be replaced in the Class::MOP
54 # bootstrap with a proper one, however we know
55 # that this one will work fine for now.
60 || confess "Can only clone an instance";
61 return bless { %{$self}, %options } => blessed($self);
64 sub initialize_instance_slot {
65 my ($self, $meta_instance, $instance, $params) = @_;
66 my $init_arg = $self->{init_arg};
67 # try to fetch the init arg from the %params ...
69 $val = $params->{$init_arg} if exists $params->{$init_arg};
70 # if nothing was in the %params, we can use the
71 # attribute's default value (if it has one)
72 if (!defined $val && defined $self->{default}) {
73 $val = $self->default($instance);
75 $meta_instance->set_slot_value($instance, $self->name, $val);
79 # the next bunch of methods will get bootstrapped
80 # away in the Class::MOP bootstrapping section
82 sub name { $_[0]->{name} }
84 sub associated_class { $_[0]->{associated_class} }
86 sub has_accessor { defined($_[0]->{accessor}) ? 1 : 0 }
87 sub has_reader { defined($_[0]->{reader}) ? 1 : 0 }
88 sub has_writer { defined($_[0]->{writer}) ? 1 : 0 }
89 sub has_predicate { defined($_[0]->{predicate}) ? 1 : 0 }
90 sub has_clearer { defined($_[0]->{clearer}) ? 1 : 0 }
91 sub has_init_arg { defined($_[0]->{init_arg}) ? 1 : 0 }
92 sub has_default { defined($_[0]->{default}) ? 1 : 0 }
94 sub accessor { $_[0]->{accessor} }
95 sub reader { $_[0]->{reader} }
96 sub writer { $_[0]->{writer} }
97 sub predicate { $_[0]->{predicate} }
98 sub clearer { $_[0]->{clearer} }
99 sub init_arg { $_[0]->{init_arg} }
101 # end bootstrapped away method section.
102 # (all methods below here are kept intact)
104 sub is_default_a_coderef {
105 (reftype($_[0]->{default}) && reftype($_[0]->{default}) eq 'CODE')
109 my ($self, $instance) = @_;
110 if ($instance && $self->is_default_a_coderef) {
111 # if the default is a CODE ref, then
112 # we pass in the instance and default
113 # can return a value based on that
114 # instance. Somewhat crude, but works.
115 return $self->{default}->($instance);
122 sub slots { (shift)->name }
126 sub attach_to_class {
127 my ($self, $class) = @_;
128 (blessed($class) && $class->isa('Class::MOP::Class'))
129 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
130 weaken($self->{associated_class} = $class);
133 sub detach_from_class {
135 $self->{associated_class} = undef;
141 my ( $self, $instance, $value ) = @_;
143 Class::MOP::Class->initialize(Scalar::Util::blessed($instance))
145 ->set_slot_value( $instance, $self->name, $value );
149 my ( $self, $instance ) = @_;
151 Class::MOP::Class->initialize(Scalar::Util::blessed($instance))
153 ->get_slot_value( $instance, $self->name );
156 ## Method generation helpers
158 sub generate_accessor_method {
161 $attr->set_value( $_[0], $_[1] ) if scalar(@_) == 2;
162 $attr->get_value( $_[0] );
166 sub generate_accessor_method_inline {
168 my $attr_name = $self->name;
169 my $meta_instance = $self->associated_class->instance_metaclass;
171 my $code = eval 'sub {'
172 . $meta_instance->inline_set_slot_value('$_[0]', "'$attr_name'", '$_[1]') . ' if scalar(@_) == 2; '
173 . $meta_instance->inline_get_slot_value('$_[0]', "'$attr_name'")
175 confess "Could not generate inline accessor because : $@" if $@;
180 sub generate_reader_method {
183 confess "Cannot assign a value to a read-only accessor" if @_ > 1;
184 $attr->get_value( $_[0] );
188 sub generate_reader_method_inline {
190 my $attr_name = $self->name;
191 my $meta_instance = $self->associated_class->instance_metaclass;
193 my $code = eval 'sub {'
194 . 'confess "Cannot assign a value to a read-only accessor" if @_ > 1;'
195 . $meta_instance->inline_get_slot_value('$_[0]', "'$attr_name'")
197 confess "Could not generate inline accessor because : $@" if $@;
202 sub generate_writer_method {
205 $attr->set_value( $_[0], $_[1] );
209 sub generate_writer_method_inline {
211 my $attr_name = $self->name;
212 my $meta_instance = $self->associated_class->instance_metaclass;
214 my $code = eval 'sub {'
215 . $meta_instance->inline_set_slot_value('$_[0]', "'$attr_name'", '$_[1]')
217 confess "Could not generate inline accessor because : $@" if $@;
222 sub generate_predicate_method {
224 my $attr_name = $self->name;
226 defined Class::MOP::Class->initialize(Scalar::Util::blessed($_[0]))
228 ->get_slot_value($_[0], $attr_name) ? 1 : 0;
232 sub generate_clearer_method {
234 my $attr_name = $self->name;
236 Class::MOP::Class->initialize(Scalar::Util::blessed($_[0]))
238 ->deinitialize_slot($_[0], $attr_name);
242 sub generate_predicate_method_inline {
244 my $attr_name = $self->name;
245 my $meta_instance = $self->associated_class->instance_metaclass;
247 my $code = eval 'sub {'
248 . 'defined ' . $meta_instance->inline_get_slot_value('$_[0]', "'$attr_name'") . ' ? 1 : 0'
250 confess "Could not generate inline predicate because : $@" if $@;
255 sub generate_clearer_method_inline {
257 my $attr_name = $self->name;
258 my $meta_instance = $self->associated_class->instance_metaclass;
260 my $code = eval 'sub {'
261 . $meta_instance->inline_deinitialize_slot('$_[0]', "'$attr_name'")
263 confess "Could not generate inline clearer because : $@" if $@;
268 sub process_accessors {
269 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
270 if (reftype($accessor)) {
271 (reftype($accessor) eq 'HASH')
272 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
273 my ($name, $method) = %{$accessor};
274 return ($name, Class::MOP::Attribute::Accessor->wrap($method));
277 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
278 my $generator = $self->can('generate_' . $type . '_method' . ($inline_me ? '_inline' : ''));
280 || confess "There is no method generator for the type='$type'";
281 if (my $method = $self->$generator($self->name)) {
282 return ($accessor => Class::MOP::Attribute::Accessor->wrap($method));
284 confess "Could not create the '$type' method for " . $self->name . " because : $@";
288 sub install_accessors {
291 my $class = $self->associated_class;
294 $self->process_accessors('accessor' => $self->accessor(), $inline)
295 ) if $self->has_accessor();
298 $self->process_accessors('reader' => $self->reader(), $inline)
299 ) if $self->has_reader();
302 $self->process_accessors('writer' => $self->writer(), $inline)
303 ) if $self->has_writer();
306 $self->process_accessors('predicate' => $self->predicate(), $inline)
307 ) if $self->has_predicate();
310 $self->process_accessors('clearer' => $self->clearer(), $inline)
311 ) if $self->has_clearer();
317 my $_remove_accessor = sub {
318 my ($accessor, $class) = @_;
319 if (reftype($accessor) && reftype($accessor) eq 'HASH') {
320 ($accessor) = keys %{$accessor};
322 my $method = $class->get_method($accessor);
323 $class->remove_method($accessor)
324 if (blessed($method) && $method->isa('Class::MOP::Attribute::Accessor'));
327 sub remove_accessors {
329 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
330 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
331 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
332 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
333 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
339 package Class::MOP::Attribute::Accessor;
344 use Class::MOP::Method;
346 our $VERSION = '0.01';
348 our @ISA = ('Class::MOP::Method');
358 Class::MOP::Attribute - Attribute Meta Object
362 Class::MOP::Attribute->new('$foo' => (
363 accessor => 'foo', # dual purpose get/set accessor
364 predicate => 'has_foo' # predicate check for defined-ness
365 init_arg => '-foo', # class->new will look for a -foo key
366 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
369 Class::MOP::Attribute->new('$.bar' => (
370 reader => 'bar', # getter
371 writer => 'set_bar', # setter
372 predicate => 'has_bar' # predicate check for defined-ness
373 init_arg => ':bar', # class->new will look for a :bar key
374 # no default value means it is undef
379 The Attribute Protocol is almost entirely an invention of this module,
380 and is completely optional to this MOP. This is because Perl 5 does not
381 have consistent notion of what is an attribute of a class. There are
382 so many ways in which this is done, and very few (if any) are
383 easily discoverable by this module.
385 So, all that said, this module attempts to inject some order into this
386 chaos, by introducing a consistent API which can be used to create
395 =item B<new ($name, ?%options)>
397 An attribute must (at the very least), have a C<$name>. All other
398 C<%options> are contained added as key-value pairs. Acceptable keys
405 This should be a string value representing the expected key in
406 an initialization hash. For instance, if we have an I<init_arg>
407 value of C<-foo>, then the following code will Just Work.
409 MyClass->meta->construct_instance(-foo => "Hello There");
411 In an init_arg is not assigned, it will automatically use the
416 The value of this key is the default value which
417 C<Class::MOP::Class::construct_instance> will initialize the
421 If the value is a simple scalar (string or number), then it can
422 be just passed as is. However, if you wish to initialize it with
423 a HASH or ARRAY ref, then you need to wrap that inside a CODE
426 Class::MOP::Attribute->new('@foo' => (
427 default => sub { [] },
432 Class::MOP::Attribute->new('%foo' => (
433 default => sub { {} },
436 If you wish to initialize an attribute with a CODE reference
437 itself, then you need to wrap that in a subroutine as well, like
440 Class::MOP::Attribute->new('&foo' => (
441 default => sub { sub { print "Hello World" } },
444 And lastly, if the value of your attribute is dependent upon
445 some other aspect of the instance structure, then you can take
446 advantage of the fact that when the I<default> value is a CODE
447 reference, it is passed the raw (unblessed) instance structure
448 as it's only argument. So you can do things like this:
450 Class::MOP::Attribute->new('$object_identity' => (
451 default => sub { Scalar::Util::refaddr($_[0]) },
454 This last feature is fairly limited as there is no gurantee of
455 the order of attribute initializations, so you cannot perform
456 any kind of dependent initializations. However, if this is
457 something you need, you could subclass B<Class::MOP::Class> and
458 this class to acheive it. However, this is currently left as
459 an exercise to the reader :).
463 The I<accessor>, I<reader>, I<writer>, I<predicate> and I<clearer> keys can
464 contain either; the name of the method and an appropriate default one will be
465 generated for you, B<or> a HASH ref containing exactly one key (which will be
466 used as the name of the method) and one value, which should contain a CODE
467 reference which will be installed as the method itself.
473 The I<accessor> is a standard perl-style read/write accessor. It will
474 return the value of the attribute, and if a value is passed as an argument,
475 it will assign that value to the attribute.
478 This method will properly handle the following code, by assigning an
479 C<undef> value to the attribute.
481 $object->set_something(undef);
485 This is a basic read-only accessor, it will just return the value of
490 This is a basic write accessor, it accepts a single argument, and
491 assigns that value to the attribute. This method does not intentially
492 return a value, however perl will return the result of the last
493 expression in the subroutine, which returns in this returning the
494 same value that it was passed.
497 This method will properly handle the following code, by assigning an
498 C<undef> value to the attribute.
500 $object->set_something();
504 This is a basic test to see if the value of the attribute is not
505 C<undef>. It will return true (C<1>) if the attribute's value is
506 defined, and false (C<0>) otherwise.
510 This is the a method that will uninitialize the attr, reverting lazy values
511 back to their "unfulfilled" state.
515 =item B<clone (%options)>
517 =item B<initialize_instance_slot ($instance, $params)>
521 =head2 Value management
525 =item set_value $instance, $value
527 Set the value without going through the accessor. Note that this may be done to
528 even attributes with just read only accessors.
530 =item get_value $instance
532 Return the value without going through the accessor. Note that this may be done
533 even to attributes with just write only accessors.
539 These are all basic read-only value accessors for the values
540 passed into C<new>. I think they are pretty much self-explanitory.
558 =item B<is_default_a_coderef>
560 =item B<default (?$instance)>
562 As noted in the documentation for C<new> above, if the I<default>
563 value is a CODE reference, this accessor will pass a single additional
564 argument C<$instance> into it and return the value.
568 Returns a list of slots required by the attribute. This is usually
569 just one, which is the name of the attribute.
573 =head2 Informational predicates
575 These are all basic predicate methods for the values passed into C<new>.
579 =item B<has_accessor>
585 =item B<has_predicate>
589 =item B<has_init_arg>
595 =head2 Class association
599 =item B<associated_class>
601 =item B<attach_to_class ($class)>
603 =item B<detach_from_class>
607 =item B<allocate_slots>
609 =item B<deallocate_slots>
613 =head2 Attribute Accessor generation
617 =item B<install_accessors>
619 This allows the attribute to generate and install code for it's own
620 I<accessor/reader/writer/predicate> methods. This is called by
621 C<Class::MOP::Class::add_attribute>.
623 This method will call C<process_accessors> for each of the possible
624 method types (accessor, reader, writer & predicate).
626 =item B<process_accessors ($type, $value)>
628 This takes a C<$type> (accessor, reader, writer or predicate), and
629 a C<$value> (the value passed into the constructor for each of the
630 different types). It will then either generate the method itself
631 (using the C<generate_*_method> methods listed below) or it will
632 use the custom method passed through the constructor.
636 =item B<generate_accessor_method>
638 =item B<generate_predicate_method>
640 =item B<generate_clearer_method>
642 =item B<generate_reader_method>
644 =item B<generate_writer_method>
650 =item B<generate_accessor_method_inline>
652 =item B<generate_predicate_method_inline>
654 =item B<generate_clearer_method_inline>
656 =item B<generate_reader_method_inline>
658 =item B<generate_writer_method_inline>
662 =item B<remove_accessors>
664 This allows the attribute to remove the method for it's own
665 I<accessor/reader/writer/predicate/clearer>. This is called by
666 C<Class::MOP::Class::remove_attribute>.
676 This will return a B<Class::MOP::Class> instance which is related
679 It should also be noted that B<Class::MOP> will actually bootstrap
680 this module by installing a number of attribute meta-objects into
681 it's metaclass. This will allow this class to reap all the benifits
682 of the MOP when subclassing it.
688 Stevan Little E<lt>stevan@iinteractive.comE<gt>
690 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
692 =head1 COPYRIGHT AND LICENSE
694 Copyright 2006 by Infinity Interactive, Inc.
696 L<http://www.iinteractive.com>
698 This library is free software; you can redistribute it and/or modify
699 it under the same terms as Perl itself.