whole bunch of stuff
[gitmo/Class-MOP.git] / lib / Class / MOP / Attribute.pm
CommitLineData
8b978dd5 1
2package Class::MOP::Attribute;
3
4use strict;
5use warnings;
6
2eb717d5 7use Carp 'confess';
9ec169fe 8use Scalar::Util 'blessed', 'reftype', 'weaken';
2eb717d5 9
5659d76e 10our $VERSION = '0.03';
8b978dd5 11
727919c5 12sub meta {
13 require Class::MOP::Class;
14 Class::MOP::Class->initialize($_[0])
15}
2eb717d5 16
727919c5 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
24# meta-objects.
25# - Ain't meta-circularity grand? :)
8b978dd5 26sub new {
27 my $class = shift;
28 my $name = shift;
29 my %options = @_;
30
cbd9f942 31 (defined $name && $name)
8b978dd5 32 || confess "You must provide a name for the attribute";
5659d76e 33 $options{init_arg} = $name
34 if not exists $options{init_arg};
2eb717d5 35
8b978dd5 36 bless {
c50c603e 37 name => $name,
38 accessor => $options{accessor},
39 reader => $options{reader},
40 writer => $options{writer},
41 predicate => $options{predicate},
42 init_arg => $options{init_arg},
9ec169fe 43 default => $options{default},
44 # keep a weakened link to the
45 # class we are associated with
46 associated_class => undef,
8b978dd5 47 } => $class;
48}
49
7b31baf4 50# NOTE:
5659d76e 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.
55sub clone {
56 my $self = shift;
57 my %options = @_;
58 (blessed($self))
59 || confess "Can only clone an instance";
60 return bless { %{$self}, %options } => blessed($self);
61}
62
63# NOTE:
7b31baf4 64# the next bunch of methods will get bootstrapped
65# away in the Class::MOP bootstrapping section
66
c50c603e 67sub name { $_[0]->{name} }
68
7b31baf4 69sub associated_class { $_[0]->{associated_class} }
70
727919c5 71sub has_accessor { defined($_[0]->{accessor}) ? 1 : 0 }
72sub has_reader { defined($_[0]->{reader}) ? 1 : 0 }
73sub has_writer { defined($_[0]->{writer}) ? 1 : 0 }
c50c603e 74sub has_predicate { defined($_[0]->{predicate}) ? 1 : 0 }
727919c5 75sub has_init_arg { defined($_[0]->{init_arg}) ? 1 : 0 }
76sub has_default { defined($_[0]->{default}) ? 1 : 0 }
c50c603e 77
78sub accessor { $_[0]->{accessor} }
79sub reader { $_[0]->{reader} }
80sub writer { $_[0]->{writer} }
81sub predicate { $_[0]->{predicate} }
82sub init_arg { $_[0]->{init_arg} }
83
7b31baf4 84# end bootstrapped away method section.
85# (all methods below here are kept intact)
86
c50c603e 87sub default {
88 my $self = shift;
89 if (reftype($self->{default}) && reftype($self->{default}) eq 'CODE') {
727919c5 90 # if the default is a CODE ref, then
91 # we pass in the instance and default
92 # can return a value based on that
93 # instance. Somewhat crude, but works.
c50c603e 94 return $self->{default}->(shift);
95 }
96 $self->{default};
97}
8b978dd5 98
9ec169fe 99# class association
727919c5 100
9ec169fe 101sub attach_to_class {
102 my ($self, $class) = @_;
103 (blessed($class) && $class->isa('Class::MOP::Class'))
104 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
105 weaken($self->{associated_class} = $class);
106}
107
108sub detach_from_class {
109 my $self = shift;
110 $self->{associated_class} = undef;
111}
112
113## Method generation helpers
114
115sub generate_accessor_method {
116 my ($self, $attr_name) = @_;
117 eval qq{sub {
118 \$_[0]->{'$attr_name'} = \$_[1] if scalar(\@_) == 2;
119 \$_[0]->{'$attr_name'};
120 }};
121}
122
123sub generate_reader_method {
124 my ($self, $attr_name) = @_;
125 eval qq{sub {
126 \$_[0]->{'$attr_name'};
127 }};
128}
129
130sub generate_writer_method {
131 my ($self, $attr_name) = @_;
132 eval qq{sub {
133 \$_[0]->{'$attr_name'} = \$_[1];
134 }};
135}
136
137sub generate_predicate_method {
138 my ($self, $attr_name) = @_;
139 eval qq{sub {
140 defined \$_[0]->{'$attr_name'} ? 1 : 0;
141 }};
142}
143
144sub process_accessors {
145 my ($self, $type, $accessor) = @_;
146 if (reftype($accessor) && reftype($accessor) eq 'HASH') {
147 my ($name, $method) = each %{$accessor};
148 return ($name, Class::MOP::Attribute::Accessor->wrap($method));
2eb717d5 149 }
9ec169fe 150 else {
151 my $generator = $self->can('generate_' . $type . '_method');
152 ($generator)
153 || confess "There is no method generator for the type='$type'";
154 if (my $method = $self->$generator($self->name)) {
155 return ($accessor => Class::MOP::Attribute::Accessor->wrap($method));
156 }
343203ee 157 confess "Could not create the '$type' method for " . $self->name . " because : $@";
9ec169fe 158 }
159}
160
161sub install_accessors {
162 my $self = shift;
163 my $class = $self->associated_class;
c50c603e 164
9ec169fe 165 $class->add_method(
166 $self->process_accessors('accessor' => $self->accessor())
167 ) if $self->has_accessor();
168
169 $class->add_method(
170 $self->process_accessors('reader' => $self->reader())
171 ) if $self->has_reader();
172
173 $class->add_method(
174 $self->process_accessors('writer' => $self->writer())
175 ) if $self->has_writer();
176
177 $class->add_method(
178 $self->process_accessors('predicate' => $self->predicate())
179 ) if $self->has_predicate();
180 return;
2eb717d5 181}
182
b51af7f9 183{
184 my $_remove_accessor = sub {
185 my ($accessor, $class) = @_;
c50c603e 186 if (reftype($accessor) && reftype($accessor) eq 'HASH') {
187 ($accessor) = keys %{$accessor};
188 }
b51af7f9 189 my $method = $class->get_method($accessor);
190 $class->remove_method($accessor)
2eb717d5 191 if (blessed($method) && $method->isa('Class::MOP::Attribute::Accessor'));
b51af7f9 192 };
c50c603e 193
b51af7f9 194 sub remove_accessors {
9ec169fe 195 my $self = shift;
196 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
197 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
198 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
199 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
b51af7f9 200 return;
201 }
202
8b978dd5 203}
204
2eb717d5 205package Class::MOP::Attribute::Accessor;
206
207use strict;
208use warnings;
209
727919c5 210use Class::MOP::Method;
211
2eb717d5 212our $VERSION = '0.01';
213
214our @ISA = ('Class::MOP::Method');
215
8b978dd5 2161;
217
218__END__
219
220=pod
221
222=head1 NAME
223
224Class::MOP::Attribute - Attribute Meta Object
225
226=head1 SYNOPSIS
227
228 Class::MOP::Attribute->new('$foo' => (
fe122940 229 accessor => 'foo', # dual purpose get/set accessor
230 predicate => 'has_foo' # predicate check for defined-ness
231 init_arg => '-foo', # class->new will look for a -foo key
232 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
8b978dd5 233 ));
234
235 Class::MOP::Attribute->new('$.bar' => (
fe122940 236 reader => 'bar', # getter
237 writer => 'set_bar', # setter
238 predicate => 'has_bar' # predicate check for defined-ness
239 init_arg => ':bar', # class->new will look for a :bar key
8b978dd5 240 # no default value means it is undef
241 ));
242
243=head1 DESCRIPTION
244
fe122940 245The Attribute Protocol is almost entirely an invention of this module,
246and is completely optional to this MOP. This is because Perl 5 does not
247have consistent notion of what is an attribute of a class. There are
248so many ways in which this is done, and very few (if any) are
249easily discoverable by this module.
552e3d24 250
251So, all that said, this module attempts to inject some order into this
fe122940 252chaos, by introducing a consistent API which can be used to create
253object attributes.
552e3d24 254
255=head1 METHODS
256
257=head2 Creation
258
259=over 4
260
fe122940 261=item B<new ($name, ?%options)>
262
263An attribute must (at the very least), have a C<$name>. All other
a2e85e6c 264C<%options> are contained added as key-value pairs. Acceptable keys
fe122940 265are as follows:
266
5659d76e 267=item B<clone (%options)>
268
fe122940 269=over 4
270
271=item I<init_arg>
272
273This should be a string value representing the expected key in
274an initialization hash. For instance, if we have an I<init_arg>
275value of C<-foo>, then the following code will Just Work.
276
277 MyClass->meta->construct_instance(-foo => "Hello There");
278
7b31baf4 279In an init_arg is not assigned, it will automatically use the
280value of C<$name>.
281
fe122940 282=item I<default>
283
284The value of this key is the default value which
285C<Class::MOP::Class::construct_instance> will initialize the
286attribute to.
287
288B<NOTE:>
289If the value is a simple scalar (string or number), then it can
290be just passed as is. However, if you wish to initialize it with
291a HASH or ARRAY ref, then you need to wrap that inside a CODE
292reference, like so:
293
294 Class::MOP::Attribute->new('@foo' => (
295 default => sub { [] },
296 ));
297
298 # or ...
299
300 Class::MOP::Attribute->new('%foo' => (
301 default => sub { {} },
302 ));
303
304If you wish to initialize an attribute with a CODE reference
305itself, then you need to wrap that in a subroutine as well, like
306so:
307
308 Class::MOP::Attribute->new('&foo' => (
309 default => sub { sub { print "Hello World" } },
310 ));
311
312And lastly, if the value of your attribute is dependent upon
313some other aspect of the instance structure, then you can take
314advantage of the fact that when the I<default> value is a CODE
315reference, it is passed the raw (unblessed) instance structure
316as it's only argument. So you can do things like this:
317
318 Class::MOP::Attribute->new('$object_identity' => (
319 default => sub { Scalar::Util::refaddr($_[0]) },
320 ));
321
322This last feature is fairly limited as there is no gurantee of
323the order of attribute initializations, so you cannot perform
324any kind of dependent initializations. However, if this is
325something you need, you could subclass B<Class::MOP::Class> and
326this class to acheive it. However, this is currently left as
327an exercise to the reader :).
328
329=back
330
a2e85e6c 331The I<accessor>, I<reader>, I<writer> and I<predicate> keys can
fe122940 332contain either; the name of the method and an appropriate default
333one will be generated for you, B<or> a HASH ref containing exactly one
334key (which will be used as the name of the method) and one value,
335which should contain a CODE reference which will be installed as
336the method itself.
59e7697f 337
338=over 4
339
340=item I<accessor>
341
fe122940 342The I<accessor> is a standard perl-style read/write accessor. It will
343return the value of the attribute, and if a value is passed as an argument,
344it will assign that value to the attribute.
345
346B<NOTE:>
347This method will properly handle the following code, by assigning an
348C<undef> value to the attribute.
349
350 $object->set_something(undef);
351
59e7697f 352=item I<reader>
353
fe122940 354This is a basic read-only accessor, it will just return the value of
355the attribute.
356
59e7697f 357=item I<writer>
358
fe122940 359This is a basic write accessor, it accepts a single argument, and
360assigns that value to the attribute. This method does not intentially
361return a value, however perl will return the result of the last
362expression in the subroutine, which returns in this returning the
363same value that it was passed.
59e7697f 364
fe122940 365B<NOTE:>
366This method will properly handle the following code, by assigning an
367C<undef> value to the attribute.
59e7697f 368
fe122940 369 $object->set_something();
370
371=item I<predicate>
372
373This is a basic test to see if the value of the attribute is not
374C<undef>. It will return true (C<1>) if the attribute's value is
375defined, and false (C<0>) otherwise.
59e7697f 376
377=back
552e3d24 378
379=back
380
381=head2 Informational
382
fe122940 383These are all basic read-only value accessors for the values
384passed into C<new>. I think they are pretty much self-explanitory.
385
552e3d24 386=over 4
387
388=item B<name>
389
390=item B<accessor>
391
392=item B<reader>
393
394=item B<writer>
395
c50c603e 396=item B<predicate>
397
552e3d24 398=item B<init_arg>
399
fe122940 400=item B<default (?$instance)>
401
402As noted in the documentation for C<new> above, if the I<default>
403value is a CODE reference, this accessor will pass a single additional
404argument C<$instance> into it and return the value.
552e3d24 405
406=back
407
408=head2 Informational predicates
409
a2e85e6c 410These are all basic predicate methods for the values passed into C<new>.
fe122940 411
552e3d24 412=over 4
413
414=item B<has_accessor>
415
552e3d24 416=item B<has_reader>
417
552e3d24 418=item B<has_writer>
419
c50c603e 420=item B<has_predicate>
421
552e3d24 422=item B<has_init_arg>
423
552e3d24 424=item B<has_default>
425
552e3d24 426=back
427
9ec169fe 428=head2 Class association
429
430=over 4
431
432=item B<associated_class>
433
434=item B<attach_to_class ($class)>
435
436=item B<detach_from_class>
437
438=back
439
552e3d24 440=head2 Attribute Accessor generation
441
442=over 4
443
9ec169fe 444=item B<install_accessors>
2eb717d5 445
446This allows the attribute to generate and install code for it's own
a2e85e6c 447I<accessor/reader/writer/predicate> methods. This is called by
fe122940 448C<Class::MOP::Class::add_attribute>.
2eb717d5 449
9ec169fe 450This method will call C<process_accessors> for each of the possible
451method types (accessor, reader, writer & predicate).
452
453=item B<process_accessors ($type, $value)>
454
455This takes a C<$type> (accessor, reader, writer or predicate), and
456a C<$value> (the value passed into the constructor for each of the
457different types). It will then either generate the method itself
458(using the C<generate_*_method> methods listed below) or it will
459use the custom method passed through the constructor.
460
461=over 4
462
463=item B<generate_accessor_method ($attr_name)>
464
465=item B<generate_predicate_method ($attr_name)>
466
467=item B<generate_reader_method ($attr_name)>
468
469=item B<generate_writer_method ($attr_name)>
470
471=back
472
473=item B<remove_accessors>
2eb717d5 474
475This allows the attribute to remove the method for it's own
a2e85e6c 476I<accessor/reader/writer/predicate>. This is called by
fe122940 477C<Class::MOP::Class::remove_attribute>.
2eb717d5 478
479=back
480
481=head2 Introspection
482
483=over 4
552e3d24 484
2eb717d5 485=item B<meta>
552e3d24 486
fe122940 487This will return a B<Class::MOP::Class> instance which is related
488to this class.
489
490It should also be noted that B<Class::MOP> will actually bootstrap
491this module by installing a number of attribute meta-objects into
492it's metaclass. This will allow this class to reap all the benifits
493of the MOP when subclassing it.
494
552e3d24 495=back
496
8b978dd5 497=head1 AUTHOR
498
a2e85e6c 499Stevan Little E<lt>stevan@iinteractive.comE<gt>
8b978dd5 500
501=head1 COPYRIGHT AND LICENSE
502
503Copyright 2006 by Infinity Interactive, Inc.
504
505L<http://www.iinteractive.com>
506
507This library is free software; you can redistribute it and/or modify
508it under the same terms as Perl itself.
509
9ec169fe 510=cut