head1 is capitalized
[p5sagit/Class-Accessor-Grouped.git] / lib / Class / Accessor / Grouped.pm
CommitLineData
963a69a5 1package Class::Accessor::Grouped;
2use strict;
3use warnings;
a0bce8bc 4use Carp ();
331e820d 5use Class::Inspector ();
a0bce8bc 6use Scalar::Util ();
8787799c 7use MRO::Compat;
1ee74bdd 8use Sub::Name ();
331e820d 9
af169484 10our $VERSION = '0.09003';
15cf8e32 11$VERSION = eval $VERSION;
963a69a5 12
a2537c55 13# Class::XSAccessor is segfaulting on win32, so be careful
14# Win32 users can set $hasXS to try to use it anyway
af169484 15
a2537c55 16our $hasXS;
af169484 17
a2537c55 18sub _hasXS {
19
20 if (not defined $hasXS) {
21 $hasXS = 0;
22
23 if ($^O ne 'MSWin32') {
24 eval {
25 require Class::XSAccessor;
26 $hasXS = 1;
27 };
28 }
29 }
30
31 return $hasXS;
32}
33
963a69a5 34=head1 NAME
35
1ad8d8c6 36Class::Accessor::Grouped - Lets you build groups of accessors
963a69a5 37
38=head1 SYNOPSIS
39
40=head1 DESCRIPTION
41
42This class lets you build groups of accessors that will call different
43getters and setters.
44
45=head1 METHODS
46
47=head2 mk_group_accessors
48
49=over 4
50
51=item Arguments: $group, @fieldspec
52
53Returns: none
54
55=back
56
57Creates a set of accessors in a given group.
58
59$group is the name of the accessor group for the generated accessors; they
60will call get_$group($field) on get and set_$group($field, $value) on set.
61
22fa6720 62If you want to mimic Class::Accessor's mk_accessors $group has to be 'simple'
63to tell Class::Accessor::Grouped to use its own get_simple and set_simple
64methods.
65
963a69a5 66@fieldspec is a list of field/accessor names; if a fieldspec is a scalar
67this is used as both field and accessor name, if a listref it is expected to
68be of the form [ $accessor, $field ].
69
70=cut
71
72sub mk_group_accessors {
73 my ($self, $group, @fields) = @_;
74
75 $self->_mk_group_accessors('make_group_accessor', $group, @fields);
76 return;
77}
78
79
80{
81 no strict 'refs';
82 no warnings 'redefine';
83
84 sub _mk_group_accessors {
85 my($self, $maker, $group, @fields) = @_;
a0bce8bc 86 my $class = Scalar::Util::blessed $self || $self;
963a69a5 87
88 # So we don't have to do lots of lookups inside the loop.
89 $maker = $self->can($maker) unless ref $maker;
9540f4e4 90
91 my $hasXS = _hasXS();
963a69a5 92
93 foreach my $field (@fields) {
94 if( $field eq 'DESTROY' ) {
a0bce8bc 95 Carp::carp("Having a data accessor named DESTROY in ".
963a69a5 96 "'$class' is unwise.");
97 }
98
99 my $name = $field;
100
101 ($name, $field) = @$field if ref $field;
9540f4e4 102
963a69a5 103 my $alias = "_${name}_accessor";
1ee74bdd 104 my $full_name = join('::', $class, $name);
105 my $full_alias = join('::', $class, $alias);
9540f4e4 106
107 if ( $hasXS && $group eq 'simple' ) {
46f1ef81 108 require Class::XSAccessor;
9540f4e4 109 Class::XSAccessor::newxs_accessor("${class}::${name}", $field, 0);
110 Class::XSAccessor::newxs_accessor("${class}::${alias}", $field, 0);
111
112 # XXX: is the alias accessor really necessary?
113 }
114 else {
115 my $accessor = $self->$maker($group, $field);
116 my $alias_accessor = $self->$maker($group, $field);
117
118 *$full_name = Sub::Name::subname($full_name, $accessor);
119 #unless defined &{$class."\:\:$field"}
120
121 *$full_alias = Sub::Name::subname($full_alias, $alias_accessor);
122 #unless defined &{$class."\:\:$alias"}
123 }
963a69a5 124 }
125 }
126}
127
128=head2 mk_group_ro_accessors
129
130=over 4
131
132=item Arguments: $group, @fieldspec
133
134Returns: none
135
136=back
137
138Creates a set of read only accessors in a given group. Identical to
a557f8ad 139L</mk_group_accessors> but accessors will throw an error if passed a value
963a69a5 140rather than setting the value.
141
142=cut
143
144sub mk_group_ro_accessors {
145 my($self, $group, @fields) = @_;
146
147 $self->_mk_group_accessors('make_group_ro_accessor', $group, @fields);
148}
149
150=head2 mk_group_wo_accessors
151
152=over 4
153
154=item Arguments: $group, @fieldspec
155
156Returns: none
157
158=back
159
160Creates a set of write only accessors in a given group. Identical to
a557f8ad 161L</mk_group_accessors> but accessors will throw an error if not passed a
963a69a5 162value rather than getting the value.
163
164=cut
165
166sub mk_group_wo_accessors {
167 my($self, $group, @fields) = @_;
168
169 $self->_mk_group_accessors('make_group_wo_accessor', $group, @fields);
170}
171
172=head2 make_group_accessor
173
174=over 4
175
176=item Arguments: $group, $field
177
178Returns: $sub (\CODE)
179
180=back
181
182Returns a single accessor in a given group; called by mk_group_accessors
183for each entry in @fieldspec.
184
185=cut
186
187sub make_group_accessor {
188 my ($class, $group, $field) = @_;
189
190 my $set = "set_$group";
191 my $get = "get_$group";
192
a0bce8bc 193 # eval for faster fastiness
194 return eval "sub {
195 if(\@_ > 1) {
196 return shift->$set('$field', \@_);
963a69a5 197 }
198 else {
a0bce8bc 199 return shift->$get('$field');
963a69a5 200 }
a0bce8bc 201 };"
963a69a5 202}
203
204=head2 make_group_ro_accessor
205
206=over 4
207
208=item Arguments: $group, $field
209
210Returns: $sub (\CODE)
211
212=back
213
214Returns a single read-only accessor in a given group; called by
215mk_group_ro_accessors for each entry in @fieldspec.
216
217=cut
218
219sub make_group_ro_accessor {
220 my($class, $group, $field) = @_;
221
222 my $get = "get_$group";
223
a0bce8bc 224 return eval "sub {
225 if(\@_ > 1) {
226 my \$caller = caller;
227 Carp::croak(\"'\$caller' cannot alter the value of '$field' on \".
228 \"objects of class '$class'\");
963a69a5 229 }
230 else {
a0bce8bc 231 return shift->$get('$field');
963a69a5 232 }
a0bce8bc 233 };"
963a69a5 234}
235
236=head2 make_group_wo_accessor
237
238=over 4
239
240=item Arguments: $group, $field
241
242Returns: $sub (\CODE)
243
244=back
245
246Returns a single write-only accessor in a given group; called by
247mk_group_wo_accessors for each entry in @fieldspec.
248
249=cut
250
251sub make_group_wo_accessor {
252 my($class, $group, $field) = @_;
253
254 my $set = "set_$group";
255
a0bce8bc 256 return eval "sub {
257 unless (\@_ > 1) {
258 my \$caller = caller;
259 Carp::croak(\"'\$caller' cannot access the value of '$field' on \".
260 \"objects of class '$class'\");
963a69a5 261 }
262 else {
a0bce8bc 263 return shift->$set('$field', \@_);
963a69a5 264 }
a0bce8bc 265 };"
963a69a5 266}
267
268=head2 get_simple
269
270=over 4
271
272=item Arguments: $field
273
274Returns: $value
275
276=back
277
278Simple getter for hash-based objects which returns the value for the field
279name passed as an argument.
280
281=cut
282
283sub get_simple {
a0bce8bc 284 return $_[0]->{$_[1]};
963a69a5 285}
286
287=head2 set_simple
288
289=over 4
290
291=item Arguments: $field, $new_value
292
293Returns: $new_value
294
295=back
296
297Simple setter for hash-based objects which sets and then returns the value
298for the field name passed as an argument.
299
300=cut
301
302sub set_simple {
a0bce8bc 303 return $_[0]->{$_[1]} = $_[2];
963a69a5 304}
305
e6f2a0fd 306
307=head2 get_inherited
308
309=over 4
310
311=item Arguments: $field
312
313Returns: $value
314
315=back
316
331e820d 317Simple getter for Classes and hash-based objects which returns the value for
318the field name passed as an argument. This behaves much like
319L<Class::Data::Accessor> where the field can be set in a base class,
320inherited and changed in subclasses, and inherited and changed for object
321instances.
e6f2a0fd 322
323=cut
324
325sub get_inherited {
a49c32d9 326 my $class;
e6f2a0fd 327
a0bce8bc 328 if (Scalar::Util::blessed $_[0]) {
329 my $reftype = Scalar::Util::reftype $_[0];
330 $class = ref $_[0];
a49c32d9 331
a0bce8bc 332 if ($reftype eq 'HASH' && exists $_[0]->{$_[1]}) {
333 return $_[0]->{$_[1]};
a49c32d9 334 } elsif ($reftype ne 'HASH') {
a0bce8bc 335 Carp::croak('Cannot get inherited value on an object instance that is not hash-based');
e6f2a0fd 336 };
a49c32d9 337 } else {
a0bce8bc 338 $class = $_[0];
e6f2a0fd 339 };
340
341 no strict 'refs';
fe63d727 342 no warnings qw/uninitialized/;
a0bce8bc 343 return ${$class.'::__cag_'.$_[1]} if defined(${$class.'::__cag_'.$_[1]});
e6f2a0fd 344
4f8ce9da 345 # we need to be smarter about recalculation, as @ISA (thus supers) can very well change in-flight
346 my $pkg_gen = mro::get_pkg_gen ($class);
fe63d727 347 if ( ${$class.'::__cag_pkg_gen'} != $pkg_gen ) {
a0bce8bc 348 @{$class.'::__cag_supers'} = $_[0]->get_super_paths;
4f8ce9da 349 ${$class.'::__cag_pkg_gen'} = $pkg_gen;
a49c32d9 350 };
351
352 foreach (@{$class.'::__cag_supers'}) {
a0bce8bc 353 return ${$_.'::__cag_'.$_[1]} if defined(${$_.'::__cag_'.$_[1]});
e6f2a0fd 354 };
c46050d3 355
9c3d5179 356 return undef;
e6f2a0fd 357}
358
359=head2 set_inherited
360
361=over 4
362
363=item Arguments: $field, $new_value
364
365Returns: $new_value
366
367=back
368
331e820d 369Simple setter for Classes and hash-based objects which sets and then returns
370the value for the field name passed as an argument. When called on a hash-based
371object it will set the appropriate hash key value. When called on a class, it
372will set a class level variable.
e6f2a0fd 373
331e820d 374B<Note:>: This method will die if you try to set an object variable on a non
375hash-based object.
e6f2a0fd 376
377=cut
378
379sub set_inherited {
a0bce8bc 380 if (Scalar::Util::blessed $_[0]) {
381 if (Scalar::Util::reftype $_[0] eq 'HASH') {
382 return $_[0]->{$_[1]} = $_[2];
e6f2a0fd 383 } else {
a0bce8bc 384 Carp::croak('Cannot set inherited value on an object instance that is not hash-based');
e6f2a0fd 385 };
386 } else {
387 no strict 'refs';
388
a0bce8bc 389 return ${$_[0].'::__cag_'.$_[1]} = $_[2];
e6f2a0fd 390 };
391}
392
331e820d 393=head2 get_component_class
394
395=over 4
396
397=item Arguments: $field
398
399Returns: $value
400
401=back
402
403Gets the value of the specified component class.
404
405 __PACKAGE__->mk_group_accessors('component_class' => 'result_class');
97d76fb4 406
331e820d 407 $self->result_class->method();
97d76fb4 408
331e820d 409 ## same as
410 $self->get_component_class('result_class')->method();
411
412=cut
413
414sub get_component_class {
a0bce8bc 415 return $_[0]->get_inherited($_[1]);
331e820d 416};
417
418=head2 set_component_class
419
420=over 4
421
422=item Arguments: $field, $class
423
424Returns: $new_value
425
426=back
427
428Inherited accessor that automatically loads the specified class before setting
429it. This method will die if the specified class could not be loaded.
430
431 __PACKAGE__->mk_group_accessors('component_class' => 'result_class');
432 __PACKAGE__->result_class('MyClass');
97d76fb4 433
331e820d 434 $self->result_class->method();
435
436=cut
437
438sub set_component_class {
a0bce8bc 439 if ($_[2]) {
bce7bdf8 440 local $^W = 0;
a0bce8bc 441 if (Class::Inspector->installed($_[2]) && !Class::Inspector->loaded($_[2])) {
442 eval "use $_[2]";
331e820d 443
a0bce8bc 444 Carp::croak("Could not load $_[1] '$_[2]': ", $@) if $@;
331e820d 445 };
446 };
447
a0bce8bc 448 return $_[0]->set_inherited($_[1], $_[2]);
331e820d 449};
450
a49c32d9 451=head2 get_super_paths
452
453Returns a list of 'parent' or 'super' class names that the current class inherited from.
454
455=cut
456
457sub get_super_paths {
a0bce8bc 458 my $class = Scalar::Util::blessed $_[0] || $_[0];
a49c32d9 459
8787799c 460 return @{mro::get_linear_isa($class)};
a49c32d9 461};
462
a2537c55 4631;
b9a69571 464
9d7d52da 465=head1 PERFORMANCE
15cf8e32 466
a2537c55 467You can speed up accessors of type 'simple' by installing L<Class::XSAccessor>.
468Note however that the use of this module is disabled by default on Win32
af169484 469systems, as it causes yet unresolved segfaults. If you are a Win32 user, and
a2537c55 470want to try this module with L<Class::XSAccessor>, set
471C<$Class::Accessor::Grouped::hasXS> to a true value B<before> registering
472your accessors (e.g. in a C<BEGIN> block)
963a69a5 473
474=head1 AUTHORS
475
476Matt S. Trout <mst@shadowcatsystems.co.uk>
97972dcb 477Christopher H. Laco <claco@chrislaco.com>
963a69a5 478
dfb86526 479With contributions from:
480
481Guillermo Roditi <groditi@cpan.org>
482
4fe25633 483=head1 COPYRIGHT & LICENSE
963a69a5 484
af169484 485Copyright (c) 2006-2010 Matt S. Trout <mst@shadowcatsystems.co.uk>
963a69a5 486
4fe25633 487This program is free software; you can redistribute it and/or modify
488it under the same terms as perl itself.
963a69a5 489
4fe25633 490=cut