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