2 package Class::MOP::Attribute;
8 use Scalar::Util 'blessed', 'reftype', 'weaken';
10 our $VERSION = '0.08';
13 require Class::MOP::Class;
14 Class::MOP::Class->initialize(blessed($_[0]) || $_[0]);
17 # NOTE: (meta-circularity)
18 # This method will be replaces 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 init_arg => $options{init_arg},
43 default => $options{default},
44 # keep a weakened link to the
45 # class we are associated with
46 associated_class => undef,
51 # this is a primative (and kludgy) clone operation
52 # for now, it will be repleace in the Class::MOP
53 # bootstrap with a proper one, however we know
54 # that this one will work fine for now.
59 || confess "Can only clone an instance";
60 return bless { %{$self}, %options } => blessed($self);
63 sub initialize_instance_slot {
64 my ($self, $meta_instance, $instance, $params) = @_;
65 my $init_arg = $self->{init_arg};
66 # try to fetch the init arg from the %params ...
68 $val = $params->{$init_arg} if exists $params->{$init_arg};
69 # if nothing was in the %params, we can use the
70 # attribute's default value (if it has one)
71 if (!defined $val && defined $self->{default}) {
72 $val = $self->default($instance);
74 $meta_instance->set_slot_value($instance, $self->name, $val);
78 # the next bunch of methods will get bootstrapped
79 # away in the Class::MOP bootstrapping section
81 sub name { $_[0]->{name} }
83 sub associated_class { $_[0]->{associated_class} }
85 sub has_accessor { defined($_[0]->{accessor}) ? 1 : 0 }
86 sub has_reader { defined($_[0]->{reader}) ? 1 : 0 }
87 sub has_writer { defined($_[0]->{writer}) ? 1 : 0 }
88 sub has_predicate { defined($_[0]->{predicate}) ? 1 : 0 }
89 sub has_init_arg { defined($_[0]->{init_arg}) ? 1 : 0 }
90 sub has_default { defined($_[0]->{default}) ? 1 : 0 }
92 sub accessor { $_[0]->{accessor} }
93 sub reader { $_[0]->{reader} }
94 sub writer { $_[0]->{writer} }
95 sub predicate { $_[0]->{predicate} }
96 sub init_arg { $_[0]->{init_arg} }
98 # end bootstrapped away method section.
99 # (all methods below here are kept intact)
103 if (reftype($self->{default}) && reftype($self->{default}) eq 'CODE') {
104 # if the default is a CODE ref, then
105 # we pass in the instance and default
106 # can return a value based on that
107 # instance. Somewhat crude, but works.
108 return $self->{default}->(shift);
115 sub slots { (shift)->name }
119 sub attach_to_class {
120 my ($self, $class) = @_;
121 (blessed($class) && $class->isa('Class::MOP::Class'))
122 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
123 weaken($self->{associated_class} = $class);
126 sub detach_from_class {
128 $self->{associated_class} = undef;
131 ## Method generation helpers
133 sub generate_accessor_method {
135 my $meta_class = $self->associated_class;
136 my $attr_name = $self->name;
138 my $meta_instance = $meta_class->initialize(Scalar::Util::blessed($_[0]))->get_meta_instance;
139 $meta_instance->set_slot_value($_[0], $attr_name, $_[1]) if scalar(@_) == 2;
140 $meta_instance->get_slot_value($_[0], $attr_name);
144 sub generate_reader_method {
146 my $meta_class = $self->associated_class;
147 my $attr_name = $self->name;
149 confess "Cannot assign a value to a read-only accessor" if @_ > 1;
150 $meta_class->initialize(Scalar::Util::blessed($_[0]))
152 ->get_slot_value($_[0], $attr_name);
156 sub generate_writer_method {
158 my $meta_class = $self->associated_class;
159 my $attr_name = $self->name;
161 $meta_class->initialize(Scalar::Util::blessed($_[0]))
163 ->set_slot_value($_[0], $attr_name, $_[1]);
167 sub generate_predicate_method {
169 my $meta_class = $self->associated_class;
170 my $attr_name = $self->name;
172 defined $meta_class->initialize(Scalar::Util::blessed($_[0]))
174 ->get_slot_value($_[0], $attr_name) ? 1 : 0;
178 sub process_accessors {
179 my ($self, $type, $accessor) = @_;
180 if (reftype($accessor)) {
181 (reftype($accessor) eq 'HASH')
182 || confess "bad accessor/reader/writer/predicate format, must be a HASH ref";
183 my ($name, $method) = each %{$accessor};
184 return ($name, Class::MOP::Attribute::Accessor->wrap($method));
187 my $generator = $self->can('generate_' . $type . '_method');
189 || confess "There is no method generator for the type='$type'";
190 if (my $method = $self->$generator($self->name)) {
191 return ($accessor => Class::MOP::Attribute::Accessor->wrap($method));
193 confess "Could not create the '$type' method for " . $self->name . " because : $@";
197 sub install_accessors {
199 my $class = $self->associated_class;
202 $self->process_accessors('accessor' => $self->accessor())
203 ) if $self->has_accessor();
206 $self->process_accessors('reader' => $self->reader())
207 ) if $self->has_reader();
210 $self->process_accessors('writer' => $self->writer())
211 ) if $self->has_writer();
214 $self->process_accessors('predicate' => $self->predicate())
215 ) if $self->has_predicate();
220 my $_remove_accessor = sub {
221 my ($accessor, $class) = @_;
222 if (reftype($accessor) && reftype($accessor) eq 'HASH') {
223 ($accessor) = keys %{$accessor};
225 my $method = $class->get_method($accessor);
226 $class->remove_method($accessor)
227 if (blessed($method) && $method->isa('Class::MOP::Attribute::Accessor'));
230 sub remove_accessors {
232 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
233 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
234 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
235 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
241 package Class::MOP::Attribute::Accessor;
246 use Class::MOP::Method;
248 our $VERSION = '0.01';
250 our @ISA = ('Class::MOP::Method');
260 Class::MOP::Attribute - Attribute Meta Object
264 Class::MOP::Attribute->new('$foo' => (
265 accessor => 'foo', # dual purpose get/set accessor
266 predicate => 'has_foo' # predicate check for defined-ness
267 init_arg => '-foo', # class->new will look for a -foo key
268 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
271 Class::MOP::Attribute->new('$.bar' => (
272 reader => 'bar', # getter
273 writer => 'set_bar', # setter
274 predicate => 'has_bar' # predicate check for defined-ness
275 init_arg => ':bar', # class->new will look for a :bar key
276 # no default value means it is undef
281 The Attribute Protocol is almost entirely an invention of this module,
282 and is completely optional to this MOP. This is because Perl 5 does not
283 have consistent notion of what is an attribute of a class. There are
284 so many ways in which this is done, and very few (if any) are
285 easily discoverable by this module.
287 So, all that said, this module attempts to inject some order into this
288 chaos, by introducing a consistent API which can be used to create
297 =item B<new ($name, ?%options)>
299 An attribute must (at the very least), have a C<$name>. All other
300 C<%options> are contained added as key-value pairs. Acceptable keys
307 This should be a string value representing the expected key in
308 an initialization hash. For instance, if we have an I<init_arg>
309 value of C<-foo>, then the following code will Just Work.
311 MyClass->meta->construct_instance(-foo => "Hello There");
313 In an init_arg is not assigned, it will automatically use the
318 The value of this key is the default value which
319 C<Class::MOP::Class::construct_instance> will initialize the
323 If the value is a simple scalar (string or number), then it can
324 be just passed as is. However, if you wish to initialize it with
325 a HASH or ARRAY ref, then you need to wrap that inside a CODE
328 Class::MOP::Attribute->new('@foo' => (
329 default => sub { [] },
334 Class::MOP::Attribute->new('%foo' => (
335 default => sub { {} },
338 If you wish to initialize an attribute with a CODE reference
339 itself, then you need to wrap that in a subroutine as well, like
342 Class::MOP::Attribute->new('&foo' => (
343 default => sub { sub { print "Hello World" } },
346 And lastly, if the value of your attribute is dependent upon
347 some other aspect of the instance structure, then you can take
348 advantage of the fact that when the I<default> value is a CODE
349 reference, it is passed the raw (unblessed) instance structure
350 as it's only argument. So you can do things like this:
352 Class::MOP::Attribute->new('$object_identity' => (
353 default => sub { Scalar::Util::refaddr($_[0]) },
356 This last feature is fairly limited as there is no gurantee of
357 the order of attribute initializations, so you cannot perform
358 any kind of dependent initializations. However, if this is
359 something you need, you could subclass B<Class::MOP::Class> and
360 this class to acheive it. However, this is currently left as
361 an exercise to the reader :).
365 The I<accessor>, I<reader>, I<writer> and I<predicate> keys can
366 contain either; the name of the method and an appropriate default
367 one will be generated for you, B<or> a HASH ref containing exactly one
368 key (which will be used as the name of the method) and one value,
369 which should contain a CODE reference which will be installed as
376 The I<accessor> is a standard perl-style read/write accessor. It will
377 return the value of the attribute, and if a value is passed as an argument,
378 it will assign that value to the attribute.
381 This method will properly handle the following code, by assigning an
382 C<undef> value to the attribute.
384 $object->set_something(undef);
388 This is a basic read-only accessor, it will just return the value of
393 This is a basic write accessor, it accepts a single argument, and
394 assigns that value to the attribute. This method does not intentially
395 return a value, however perl will return the result of the last
396 expression in the subroutine, which returns in this returning the
397 same value that it was passed.
400 This method will properly handle the following code, by assigning an
401 C<undef> value to the attribute.
403 $object->set_something();
407 This is a basic test to see if the value of the attribute is not
408 C<undef>. It will return true (C<1>) if the attribute's value is
409 defined, and false (C<0>) otherwise.
413 =item B<clone (%options)>
415 =item B<initialize_instance_slot ($instance, $params)>
421 These are all basic read-only value accessors for the values
422 passed into C<new>. I think they are pretty much self-explanitory.
438 =item B<default (?$instance)>
440 As noted in the documentation for C<new> above, if the I<default>
441 value is a CODE reference, this accessor will pass a single additional
442 argument C<$instance> into it and return the value.
446 Returns a list of slots required by the attribute. This is usually
447 just one, which is the name of the attribute.
451 =head2 Informational predicates
453 These are all basic predicate methods for the values passed into C<new>.
457 =item B<has_accessor>
463 =item B<has_predicate>
465 =item B<has_init_arg>
471 =head2 Class association
475 =item B<associated_class>
477 =item B<attach_to_class ($class)>
479 =item B<detach_from_class>
483 =item B<allocate_slots>
485 =item B<deallocate_slots>
489 =head2 Attribute Accessor generation
493 =item B<install_accessors>
495 This allows the attribute to generate and install code for it's own
496 I<accessor/reader/writer/predicate> methods. This is called by
497 C<Class::MOP::Class::add_attribute>.
499 This method will call C<process_accessors> for each of the possible
500 method types (accessor, reader, writer & predicate).
502 =item B<process_accessors ($type, $value)>
504 This takes a C<$type> (accessor, reader, writer or predicate), and
505 a C<$value> (the value passed into the constructor for each of the
506 different types). It will then either generate the method itself
507 (using the C<generate_*_method> methods listed below) or it will
508 use the custom method passed through the constructor.
512 =item B<generate_accessor_method>
514 =item B<generate_predicate_method>
516 =item B<generate_reader_method>
518 =item B<generate_writer_method>
522 =item B<remove_accessors>
524 This allows the attribute to remove the method for it's own
525 I<accessor/reader/writer/predicate>. This is called by
526 C<Class::MOP::Class::remove_attribute>.
536 This will return a B<Class::MOP::Class> instance which is related
539 It should also be noted that B<Class::MOP> will actually bootstrap
540 this module by installing a number of attribute meta-objects into
541 it's metaclass. This will allow this class to reap all the benifits
542 of the MOP when subclassing it.
548 Stevan Little E<lt>stevan@iinteractive.comE<gt>
550 =head1 COPYRIGHT AND LICENSE
552 Copyright 2006 by Infinity Interactive, Inc.
554 L<http://www.iinteractive.com>
556 This library is free software; you can redistribute it and/or modify
557 it under the same terms as Perl itself.