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