2 package Class::MOP::Attribute;
7 use Class::MOP::Method::Accessor;
10 use Scalar::Util 'blessed', 'reftype', 'weaken';
12 our $VERSION = '0.14';
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};
42 (is_default_a_coderef(\%options))
43 || confess("References are not allowed as default values, you must ".
44 "wrap then in a CODE reference (ex: sub { [] } and not [])")
45 if exists $options{default} && ref $options{default};
49 '$!accessor' => $options{accessor},
50 '$!reader' => $options{reader},
51 '$!writer' => $options{writer},
52 '$!predicate' => $options{predicate},
53 '$!clearer' => $options{clearer},
54 '$!init_arg' => $options{init_arg},
55 '$!default' => $options{default},
56 # keep a weakened link to the
57 # class we are associated with
58 '$!associated_class' => undef,
59 # and a list of the methods
60 # associated with this attr
61 '@!associated_methods' => [],
66 # this is a primative (and kludgy) clone operation
67 # for now, it will be replaced in the Class::MOP
68 # bootstrap with a proper one, however we know
69 # that this one will work fine for now.
74 || confess "Can only clone an instance";
75 return bless { %{$self}, %options } => blessed($self);
78 sub initialize_instance_slot {
79 my ($self, $meta_instance, $instance, $params) = @_;
80 my $init_arg = $self->{'$!init_arg'};
81 # try to fetch the init arg from the %params ...
83 $val = $params->{$init_arg} if exists $params->{$init_arg};
84 # if nothing was in the %params, we can use the
85 # attribute's default value (if it has one)
86 if (!defined $val && defined $self->{'$!default'}) {
87 $val = $self->default($instance);
89 $meta_instance->set_slot_value($instance, $self->name, $val);
93 # the next bunch of methods will get bootstrapped
94 # away in the Class::MOP bootstrapping section
96 sub name { $_[0]->{'$!name'} }
98 sub associated_class { $_[0]->{'$!associated_class'} }
99 sub associated_methods { $_[0]->{'@!associated_methods'} }
101 sub has_accessor { defined($_[0]->{'$!accessor'}) ? 1 : 0 }
102 sub has_reader { defined($_[0]->{'$!reader'}) ? 1 : 0 }
103 sub has_writer { defined($_[0]->{'$!writer'}) ? 1 : 0 }
104 sub has_predicate { defined($_[0]->{'$!predicate'}) ? 1 : 0 }
105 sub has_clearer { defined($_[0]->{'$!clearer'}) ? 1 : 0 }
106 sub has_init_arg { defined($_[0]->{'$!init_arg'}) ? 1 : 0 }
107 sub has_default { defined($_[0]->{'$!default'}) ? 1 : 0 }
109 sub accessor { $_[0]->{'$!accessor'} }
110 sub reader { $_[0]->{'$!reader'} }
111 sub writer { $_[0]->{'$!writer'} }
112 sub predicate { $_[0]->{'$!predicate'} }
113 sub clearer { $_[0]->{'$!clearer'} }
114 sub init_arg { $_[0]->{'$!init_arg'} }
116 # end bootstrapped away method section.
117 # (all methods below here are kept intact)
119 sub is_default_a_coderef {
120 ('CODE' eq (reftype($_[0]->{'$!default'} || $_[0]->{default}) || ''))
124 my ($self, $instance) = @_;
125 if (defined $instance && $self->is_default_a_coderef) {
126 # if the default is a CODE ref, then
127 # we pass in the instance and default
128 # can return a value based on that
129 # instance. Somewhat crude, but works.
130 return $self->{'$!default'}->($instance);
132 $self->{'$!default'};
137 sub slots { (shift)->name }
141 sub attach_to_class {
142 my ($self, $class) = @_;
143 (blessed($class) && $class->isa('Class::MOP::Class'))
144 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
145 weaken($self->{'$!associated_class'} = $class);
148 sub detach_from_class {
150 $self->{'$!associated_class'} = undef;
155 sub associate_method {
156 my ($self, $method) = @_;
157 push @{$self->{'@!associated_methods'}} => $method;
163 my ($self, $instance, $value) = @_;
165 Class::MOP::Class->initialize(blessed($instance))
167 ->set_slot_value($instance, $self->name, $value);
171 my ($self, $instance) = @_;
173 Class::MOP::Class->initialize(blessed($instance))
175 ->get_slot_value($instance, $self->name);
179 my ($self, $instance) = @_;
181 defined Class::MOP::Class->initialize(blessed($instance))
183 ->get_slot_value($instance, $self->name) ? 1 : 0;
187 my ($self, $instance) = @_;
189 Class::MOP::Class->initialize(blessed($instance))
191 ->deinitialize_slot($instance, $self->name);
196 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
198 sub process_accessors {
199 my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
200 if (reftype($accessor)) {
201 (reftype($accessor) eq 'HASH')
202 || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
203 my ($name, $method) = %{$accessor};
204 $method = $self->accessor_metaclass->wrap($method);
205 $self->associate_method($method);
206 return ($name, $method);
209 my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
212 $method = $self->accessor_metaclass->new(
214 is_inline => $inline_me,
215 accessor_type => $type,
218 confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
219 $self->associate_method($method);
220 return ($accessor, $method);
224 sub install_accessors {
227 my $class = $self->associated_class;
230 $self->process_accessors('accessor' => $self->accessor(), $inline)
231 ) if $self->has_accessor();
234 $self->process_accessors('reader' => $self->reader(), $inline)
235 ) if $self->has_reader();
238 $self->process_accessors('writer' => $self->writer(), $inline)
239 ) if $self->has_writer();
242 $self->process_accessors('predicate' => $self->predicate(), $inline)
243 ) if $self->has_predicate();
246 $self->process_accessors('clearer' => $self->clearer(), $inline)
247 ) if $self->has_clearer();
253 my $_remove_accessor = sub {
254 my ($accessor, $class) = @_;
255 if (reftype($accessor) && reftype($accessor) eq 'HASH') {
256 ($accessor) = keys %{$accessor};
258 my $method = $class->get_method($accessor);
259 $class->remove_method($accessor)
260 if (blessed($method) && $method->isa('Class::MOP::Method::Accessor'));
263 sub remove_accessors {
265 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
266 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
267 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
268 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
269 $_remove_accessor->($self->clearer(), $self->associated_class()) if $self->has_clearer();
283 Class::MOP::Attribute - Attribute Meta Object
287 Class::MOP::Attribute->new('$foo' => (
288 accessor => 'foo', # dual purpose get/set accessor
289 predicate => 'has_foo' # predicate check for defined-ness
290 init_arg => '-foo', # class->new will look for a -foo key
291 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
294 Class::MOP::Attribute->new('$.bar' => (
295 reader => 'bar', # getter
296 writer => 'set_bar', # setter
297 predicate => 'has_bar' # predicate check for defined-ness
298 init_arg => ':bar', # class->new will look for a :bar key
299 # no default value means it is undef
304 The Attribute Protocol is almost entirely an invention of this module,
305 and is completely optional to this MOP. This is because Perl 5 does not
306 have consistent notion of what is an attribute of a class. There are
307 so many ways in which this is done, and very few (if any) are
308 easily discoverable by this module.
310 So, all that said, this module attempts to inject some order into this
311 chaos, by introducing a consistent API which can be used to create
320 =item B<new ($name, ?%options)>
322 An attribute must (at the very least), have a C<$name>. All other
323 C<%options> are contained added as key-value pairs. Acceptable keys
330 This should be a string value representing the expected key in
331 an initialization hash. For instance, if we have an I<init_arg>
332 value of C<-foo>, then the following code will Just Work.
334 MyClass->meta->construct_instance(-foo => "Hello There");
336 In an init_arg is not assigned, it will automatically use the
341 The value of this key is the default value which
342 C<Class::MOP::Class::construct_instance> will initialize the
346 If the value is a simple scalar (string or number), then it can
347 be just passed as is. However, if you wish to initialize it with
348 a HASH or ARRAY ref, then you need to wrap that inside a CODE
351 Class::MOP::Attribute->new('@foo' => (
352 default => sub { [] },
357 Class::MOP::Attribute->new('%foo' => (
358 default => sub { {} },
361 If you wish to initialize an attribute with a CODE reference
362 itself, then you need to wrap that in a subroutine as well, like
365 Class::MOP::Attribute->new('&foo' => (
366 default => sub { sub { print "Hello World" } },
369 And lastly, if the value of your attribute is dependent upon
370 some other aspect of the instance structure, then you can take
371 advantage of the fact that when the I<default> value is a CODE
372 reference, it is passed the raw (unblessed) instance structure
373 as it's only argument. So you can do things like this:
375 Class::MOP::Attribute->new('$object_identity' => (
376 default => sub { Scalar::Util::refaddr($_[0]) },
379 This last feature is fairly limited as there is no gurantee of
380 the order of attribute initializations, so you cannot perform
381 any kind of dependent initializations. However, if this is
382 something you need, you could subclass B<Class::MOP::Class> and
383 this class to acheive it. However, this is currently left as
384 an exercise to the reader :).
388 The I<accessor>, I<reader>, I<writer>, I<predicate> and I<clearer> keys can
389 contain either; the name of the method and an appropriate default one will be
390 generated for you, B<or> a HASH ref containing exactly one key (which will be
391 used as the name of the method) and one value, which should contain a CODE
392 reference which will be installed as the method itself.
398 The I<accessor> is a standard perl-style read/write accessor. It will
399 return the value of the attribute, and if a value is passed as an argument,
400 it will assign that value to the attribute.
403 This method will properly handle the following code, by assigning an
404 C<undef> value to the attribute.
406 $object->set_something(undef);
410 This is a basic read-only accessor, it will just return the value of
415 This is a basic write accessor, it accepts a single argument, and
416 assigns that value to the attribute. This method does not intentially
417 return a value, however perl will return the result of the last
418 expression in the subroutine, which returns in this returning the
419 same value that it was passed.
422 This method will properly handle the following code, by assigning an
423 C<undef> value to the attribute.
425 $object->set_something();
429 This is a basic test to see if the value of the attribute is not
430 C<undef>. It will return true (C<1>) if the attribute's value is
431 defined, and false (C<0>) otherwise.
435 This is the a method that will uninitialize the attr, reverting lazy values
436 back to their "unfulfilled" state.
440 =item B<clone (%options)>
442 =item B<initialize_instance_slot ($instance, $params)>
446 =head2 Value management
450 =item B<set_value ($instance, $value)>
452 Set the value without going through the accessor. Note that this may be done to
453 even attributes with just read only accessors.
455 =item B<get_value ($instance)>
457 Return the value without going through the accessor. Note that this may be done
458 even to attributes with just write only accessors.
460 =item B<has_value ($instance)>
462 =item B<clear_value ($instance)>
468 These are all basic read-only value accessors for the values
469 passed into C<new>. I think they are pretty much self-explanitory.
487 =item B<is_default_a_coderef>
489 =item B<default (?$instance)>
491 As noted in the documentation for C<new> above, if the I<default>
492 value is a CODE reference, this accessor will pass a single additional
493 argument C<$instance> into it and return the value.
497 Returns a list of slots required by the attribute. This is usually
498 just one, which is the name of the attribute.
502 =head2 Informational predicates
504 These are all basic predicate methods for the values passed into C<new>.
508 =item B<has_accessor>
514 =item B<has_predicate>
518 =item B<has_init_arg>
524 =head2 Class association
528 =item B<associated_class>
530 =item B<attach_to_class ($class)>
532 =item B<detach_from_class>
536 =head2 Attribute Accessor generation
540 =item B<accessor_metaclass>
542 =item B<associate_method>
544 =item B<associated_methods>
546 =item B<install_accessors>
548 This allows the attribute to generate and install code for it's own
549 I<accessor/reader/writer/predicate> methods. This is called by
550 C<Class::MOP::Class::add_attribute>.
552 This method will call C<process_accessors> for each of the possible
553 method types (accessor, reader, writer & predicate).
555 =item B<process_accessors ($type, $value)>
557 This takes a C<$type> (accessor, reader, writer or predicate), and
558 a C<$value> (the value passed into the constructor for each of the
559 different types). It will then either generate the method itself
560 (using the C<generate_*_method> methods listed below) or it will
561 use the custom method passed through the constructor.
563 =item B<remove_accessors>
565 This allows the attribute to remove the method for it's own
566 I<accessor/reader/writer/predicate/clearer>. This is called by
567 C<Class::MOP::Class::remove_attribute>.
577 This will return a B<Class::MOP::Class> instance which is related
580 It should also be noted that B<Class::MOP> will actually bootstrap
581 this module by installing a number of attribute meta-objects into
582 it's metaclass. This will allow this class to reap all the benifits
583 of the MOP when subclassing it.
589 Stevan Little E<lt>stevan@iinteractive.comE<gt>
591 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
593 =head1 COPYRIGHT AND LICENSE
595 Copyright 2006 by Infinity Interactive, Inc.
597 L<http://www.iinteractive.com>
599 This library is free software; you can redistribute it and/or modify
600 it under the same terms as Perl itself.