2 package Class::MOP::Attribute;
8 use Scalar::Util 'blessed', 'reftype', 'weaken';
10 our $VERSION = '0.06';
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, $class, $instance, $params) = @_;
66 # We break the attribute encapsulation here
67 # in order to save a number of method calls
68 # to $self and speed things up a bit
69 my $init_arg = $self->{init_arg};
70 # try to fetch the init arg from the %params ...
72 $val = $params->{$init_arg} if exists $params->{$init_arg};
73 # if nothing was in the %params, we can use the
74 # attribute's default value (if it has one)
75 if (!defined $val && $self->{default}) {
76 $val = $self->default($instance);
78 $instance->{$self->{name}} = $val;
82 # the next bunch of methods will get bootstrapped
83 # away in the Class::MOP bootstrapping section
85 sub name { $_[0]->{name} }
87 sub associated_class { $_[0]->{associated_class} }
89 sub has_accessor { defined($_[0]->{accessor}) ? 1 : 0 }
90 sub has_reader { defined($_[0]->{reader}) ? 1 : 0 }
91 sub has_writer { defined($_[0]->{writer}) ? 1 : 0 }
92 sub has_predicate { defined($_[0]->{predicate}) ? 1 : 0 }
93 sub has_init_arg { defined($_[0]->{init_arg}) ? 1 : 0 }
94 sub has_default { defined($_[0]->{default}) ? 1 : 0 }
96 sub accessor { $_[0]->{accessor} }
97 sub reader { $_[0]->{reader} }
98 sub writer { $_[0]->{writer} }
99 sub predicate { $_[0]->{predicate} }
100 sub init_arg { $_[0]->{init_arg} }
102 # end bootstrapped away method section.
103 # (all methods below here are kept intact)
107 if (reftype($self->{default}) && reftype($self->{default}) eq 'CODE') {
108 # if the default is a CODE ref, then
109 # we pass in the instance and default
110 # can return a value based on that
111 # instance. Somewhat crude, but works.
112 return $self->{default}->(shift);
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 {
134 my ($self, $attr_name) = @_;
136 $_[0]->{$attr_name} = $_[1] if scalar(@_) == 2;
141 sub generate_reader_method {
142 my ($self, $attr_name) = @_;
144 confess "Cannot assign a value to a read-only accessor" if @_ > 1;
149 sub generate_writer_method {
150 my ($self, $attr_name) = @_;
151 sub { $_[0]->{$attr_name} = $_[1] };
154 sub generate_predicate_method {
155 my ($self, $attr_name) = @_;
156 sub { defined $_[0]->{$attr_name} ? 1 : 0 };
159 sub process_accessors {
160 my ($self, $type, $accessor) = @_;
161 if (reftype($accessor)) {
162 (reftype($accessor) eq 'HASH')
163 || confess "bad accessor/reader/writer/predicate format, must be a HASH ref";
164 my ($name, $method) = each %{$accessor};
165 return ($name, Class::MOP::Attribute::Accessor->wrap($method));
168 my $generator = $self->can('generate_' . $type . '_method');
170 || confess "There is no method generator for the type='$type'";
171 if (my $method = $self->$generator($self->name)) {
172 return ($accessor => Class::MOP::Attribute::Accessor->wrap($method));
174 confess "Could not create the '$type' method for " . $self->name . " because : $@";
178 sub install_accessors {
180 my $class = $self->associated_class;
183 $self->process_accessors('accessor' => $self->accessor())
184 ) if $self->has_accessor();
187 $self->process_accessors('reader' => $self->reader())
188 ) if $self->has_reader();
191 $self->process_accessors('writer' => $self->writer())
192 ) if $self->has_writer();
195 $self->process_accessors('predicate' => $self->predicate())
196 ) if $self->has_predicate();
201 my $_remove_accessor = sub {
202 my ($accessor, $class) = @_;
203 if (reftype($accessor) && reftype($accessor) eq 'HASH') {
204 ($accessor) = keys %{$accessor};
206 my $method = $class->get_method($accessor);
207 $class->remove_method($accessor)
208 if (blessed($method) && $method->isa('Class::MOP::Attribute::Accessor'));
211 sub remove_accessors {
213 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
214 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
215 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
216 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
222 package Class::MOP::Attribute::Accessor;
227 use Class::MOP::Method;
229 our $VERSION = '0.01';
231 our @ISA = ('Class::MOP::Method');
241 Class::MOP::Attribute - Attribute Meta Object
245 Class::MOP::Attribute->new('$foo' => (
246 accessor => 'foo', # dual purpose get/set accessor
247 predicate => 'has_foo' # predicate check for defined-ness
248 init_arg => '-foo', # class->new will look for a -foo key
249 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
252 Class::MOP::Attribute->new('$.bar' => (
253 reader => 'bar', # getter
254 writer => 'set_bar', # setter
255 predicate => 'has_bar' # predicate check for defined-ness
256 init_arg => ':bar', # class->new will look for a :bar key
257 # no default value means it is undef
262 The Attribute Protocol is almost entirely an invention of this module,
263 and is completely optional to this MOP. This is because Perl 5 does not
264 have consistent notion of what is an attribute of a class. There are
265 so many ways in which this is done, and very few (if any) are
266 easily discoverable by this module.
268 So, all that said, this module attempts to inject some order into this
269 chaos, by introducing a consistent API which can be used to create
278 =item B<new ($name, ?%options)>
280 An attribute must (at the very least), have a C<$name>. All other
281 C<%options> are contained added as key-value pairs. Acceptable keys
288 This should be a string value representing the expected key in
289 an initialization hash. For instance, if we have an I<init_arg>
290 value of C<-foo>, then the following code will Just Work.
292 MyClass->meta->construct_instance(-foo => "Hello There");
294 In an init_arg is not assigned, it will automatically use the
299 The value of this key is the default value which
300 C<Class::MOP::Class::construct_instance> will initialize the
304 If the value is a simple scalar (string or number), then it can
305 be just passed as is. However, if you wish to initialize it with
306 a HASH or ARRAY ref, then you need to wrap that inside a CODE
309 Class::MOP::Attribute->new('@foo' => (
310 default => sub { [] },
315 Class::MOP::Attribute->new('%foo' => (
316 default => sub { {} },
319 If you wish to initialize an attribute with a CODE reference
320 itself, then you need to wrap that in a subroutine as well, like
323 Class::MOP::Attribute->new('&foo' => (
324 default => sub { sub { print "Hello World" } },
327 And lastly, if the value of your attribute is dependent upon
328 some other aspect of the instance structure, then you can take
329 advantage of the fact that when the I<default> value is a CODE
330 reference, it is passed the raw (unblessed) instance structure
331 as it's only argument. So you can do things like this:
333 Class::MOP::Attribute->new('$object_identity' => (
334 default => sub { Scalar::Util::refaddr($_[0]) },
337 This last feature is fairly limited as there is no gurantee of
338 the order of attribute initializations, so you cannot perform
339 any kind of dependent initializations. However, if this is
340 something you need, you could subclass B<Class::MOP::Class> and
341 this class to acheive it. However, this is currently left as
342 an exercise to the reader :).
346 The I<accessor>, I<reader>, I<writer> and I<predicate> keys can
347 contain either; the name of the method and an appropriate default
348 one will be generated for you, B<or> a HASH ref containing exactly one
349 key (which will be used as the name of the method) and one value,
350 which should contain a CODE reference which will be installed as
357 The I<accessor> is a standard perl-style read/write accessor. It will
358 return the value of the attribute, and if a value is passed as an argument,
359 it will assign that value to the attribute.
362 This method will properly handle the following code, by assigning an
363 C<undef> value to the attribute.
365 $object->set_something(undef);
369 This is a basic read-only accessor, it will just return the value of
374 This is a basic write accessor, it accepts a single argument, and
375 assigns that value to the attribute. This method does not intentially
376 return a value, however perl will return the result of the last
377 expression in the subroutine, which returns in this returning the
378 same value that it was passed.
381 This method will properly handle the following code, by assigning an
382 C<undef> value to the attribute.
384 $object->set_something();
388 This is a basic test to see if the value of the attribute is not
389 C<undef>. It will return true (C<1>) if the attribute's value is
390 defined, and false (C<0>) otherwise.
394 =item B<clone (%options)>
396 =item B<initialize_instance_slot ($instance, $params)>
402 These are all basic read-only value accessors for the values
403 passed into C<new>. I think they are pretty much self-explanitory.
419 =item B<default (?$instance)>
421 As noted in the documentation for C<new> above, if the I<default>
422 value is a CODE reference, this accessor will pass a single additional
423 argument C<$instance> into it and return the value.
427 =head2 Informational predicates
429 These are all basic predicate methods for the values passed into C<new>.
433 =item B<has_accessor>
439 =item B<has_predicate>
441 =item B<has_init_arg>
447 =head2 Class association
451 =item B<associated_class>
453 =item B<attach_to_class ($class)>
455 =item B<detach_from_class>
459 =head2 Attribute Accessor generation
463 =item B<install_accessors>
465 This allows the attribute to generate and install code for it's own
466 I<accessor/reader/writer/predicate> methods. This is called by
467 C<Class::MOP::Class::add_attribute>.
469 This method will call C<process_accessors> for each of the possible
470 method types (accessor, reader, writer & predicate).
472 =item B<process_accessors ($type, $value)>
474 This takes a C<$type> (accessor, reader, writer or predicate), and
475 a C<$value> (the value passed into the constructor for each of the
476 different types). It will then either generate the method itself
477 (using the C<generate_*_method> methods listed below) or it will
478 use the custom method passed through the constructor.
482 =item B<generate_accessor_method ($attr_name)>
484 =item B<generate_predicate_method ($attr_name)>
486 =item B<generate_reader_method ($attr_name)>
488 =item B<generate_writer_method ($attr_name)>
492 =item B<remove_accessors>
494 This allows the attribute to remove the method for it's own
495 I<accessor/reader/writer/predicate>. This is called by
496 C<Class::MOP::Class::remove_attribute>.
506 This will return a B<Class::MOP::Class> instance which is related
509 It should also be noted that B<Class::MOP> will actually bootstrap
510 this module by installing a number of attribute meta-objects into
511 it's metaclass. This will allow this class to reap all the benifits
512 of the MOP when subclassing it.
518 Stevan Little E<lt>stevan@iinteractive.comE<gt>
520 =head1 COPYRIGHT AND LICENSE
522 Copyright 2006 by Infinity Interactive, Inc.
524 L<http://www.iinteractive.com>
526 This library is free software; you can redistribute it and/or modify
527 it under the same terms as Perl itself.