1Class::Accessor(3)    User Contributed Perl Documentation   Class::Accessor(3)
2
3
4

NAME

6         Class::Accessor - Automated accessor generation
7

SYNOPSIS

9         package Employee;
10         use base qw(Class::Accessor);
11         Employee->mk_accessors(qw(name role salary));
12
13         # Meanwhile, in a nearby piece of code!
14         # Class::Accessor provides new().
15         my $mp = Foo->new({ name => "Marty", role => "JAPH" });
16
17         my $job = $mp->role;  # gets $mp->{role}
18         $mp->salary(400000);  # sets $mp->{salary} = 400000 (I wish)
19
20         # like my @info = @{$mp}{qw(name role)}
21         my @info = $mp->get(qw(name role));
22
23         # $mp->{salary} = 400000
24         $mp->set('salary', 400000);
25

DESCRIPTION

27       This module automagically generates accessors/mutators for your class.
28
29       Most of the time, writing accessors is an exercise in cutting and past‐
30       ing.  You usually wind up with a series of methods like this:
31
32           sub name {
33               my $self = shift;
34               if(@_) {
35                   $self->{name} = $_[0];
36               }
37               return $self->{name};
38           }
39
40           sub salary {
41               my $self = shift;
42               if(@_) {
43                   $self->{salary} = $_[0];
44               }
45               return $self->{salary};
46           }
47
48         # etc...
49
50       One for each piece of data in your object.  While some will be unique,
51       doing value checks and special storage tricks, most will simply be
52       exercises in repetition.  Not only is it Bad Style to have a bunch of
53       repetitious code, but its also simply not lazy, which is the real
54       tragedy.
55
56       If you make your module a subclass of Class::Accessor and declare your
57       accessor fields with mk_accessors() then you'll find yourself with a
58       set of automatically generated accessors which can even be customized!
59
60       The basic set up is very simple:
61
62           package My::Class;
63           use base qw(Class::Accessor);
64           My::Class->mk_accessors( qw(foo bar car) );
65
66       Done.  My::Class now has simple foo(), bar() and car() accessors
67       defined.
68
69       What Makes This Different?
70
71       What makes this module special compared to all the other method gener‐
72       ating modules ("SEE ALSO")?  By overriding the get() and set() methods
73       you can alter the behavior of the accessors class-wide.  Also, the
74       accessors are implemented as closures which should cost a bit less mem‐
75       ory than most other solutions which generate a new method for each
76       accessor.
77

METHODS

79       new
80
81           my $obj = Class->new;
82           my $obj = $other_obj->new;
83
84           my $obj = Class->new(\%fields);
85           my $obj = $other_obj->new(\%fields);
86
87       Class::Accessor provides a basic constructor.  It generates a hash-
88       based object and can be called as either a class method or an object
89       method.
90
91       It takes an optional %fields hash which is used to initialize the
92       object (handy if you use read-only accessors).  The fields of the hash
93       correspond to the names of your accessors, so...
94
95           package Foo;
96           use base qw(Class::Accessor);
97           Foo->mk_accessors('foo');
98
99           my $obj = Class->new({ foo => 42 });
100           print $obj->foo;    # 42
101
102       however %fields can contain anything, new() will shove them all into
103       your object.  Don't like it?  Override it.
104
105       mk_accessors
106
107           Class->mk_accessors(@fields);
108
109       This creates accessor/mutator methods for each named field given in
110       @fields.  Foreach field in @fields it will generate two accessors.  One
111       called "field()" and the other called "_field_accessor()".  For exam‐
112       ple:
113
114           # Generates foo(), _foo_accessor(), bar() and _bar_accessor().
115           Class->mk_accessors(qw(foo bar));
116
117       See "Overriding autogenerated accessors" in CAVEATS AND TRICKS for
118       details.
119
120       mk_ro_accessors
121
122         Class->mk_ro_accessors(@read_only_fields);
123
124       Same as mk_accessors() except it will generate read-only accessors (ie.
125       true accessors).  If you attempt to set a value with these accessors it
126       will throw an exception.  It only uses get() and not set().
127
128           package Foo;
129           use base qw(Class::Accessor);
130           Class->mk_ro_accessors(qw(foo bar));
131
132           # Let's assume we have an object $foo of class Foo...
133           print $foo->foo;  # ok, prints whatever the value of $foo->{foo} is
134           $foo->foo(42);    # BOOM!  Naughty you.
135
136       mk_wo_accessors
137
138         Class->mk_wo_accessors(@write_only_fields);
139
140       Same as mk_accessors() except it will generate write-only accessors
141       (ie. mutators).  If you attempt to read a value with these accessors it
142       will throw an exception.  It only uses set() and not get().
143
144       NOTE I'm not entirely sure why this is useful, but I'm sure someone
145       will need it.  If you've found a use, let me know.  Right now its here
146       for orthoginality and because its easy to implement.
147
148           package Foo;
149           use base qw(Class::Accessor);
150           Class->mk_wo_accessors(qw(foo bar));
151
152           # Let's assume we have an object $foo of class Foo...
153           $foo->foo(42);      # OK.  Sets $self->{foo} = 42
154           print $foo->foo;    # BOOM!  Can't read from this accessor.
155

DETAILS

157       An accessor generated by Class::Accessor looks something like this:
158
159           # Your foo may vary.
160           sub foo {
161               my($self) = shift;
162               if(@_) {    # set
163                   return $self->set('foo', @_);
164               }
165               else {
166                   return $self->get('foo');
167               }
168           }
169
170       Very simple.  All it does is determine if you're wanting to set a value
171       or get a value and calls the appropriate method.  Class::Accessor pro‐
172       vides default get() and set() methods which your class can override.
173       They're detailed later.
174
175       follow_best_practice
176
177       In Damian's Perl Best Practices book he recommends separate get and set
178       methods with the prefix set_ and get_ to make it explicit what you
179       intend to do.  If you want to create those accessor methods instead of
180       the default ones, call:
181
182           __PACKAGE__->follow_best_practice
183
184       accessor_name_for / mutator_name_for
185
186       You may have your own crazy ideas for the names of the accessors, so
187       you can make those happen by overriding "accessor_name_for" and "muta‐
188       tor_name_for" in your subclass.  (I copied that idea from Class::DBI.)
189
190       Modifying the behavior of the accessor
191
192       Rather than actually modifying the accessor itself, it is much more
193       sensible to simply override the two key methods which the accessor
194       calls.  Namely set() and get().
195
196       If you -really- want to, you can override make_accessor().
197
198       set
199
200           $obj->set($key, $value);
201           $obj->set($key, @values);
202
203       set() defines how generally one stores data in the object.
204
205       override this method to change how data is stored by your accessors.
206
207       get
208
209           $value  = $obj->get($key);
210           @values = $obj->get(@keys);
211
212       get() defines how data is retreived from your objects.
213
214       override this method to change how it is retreived.
215
216       make_accessor
217
218           $accessor = Class->make_accessor($field);
219
220       Generates a subroutine reference which acts as an accessor for the
221       given $field.  It calls get() and set().
222
223       If you wish to change the behavior of your accessors, try overriding
224       get() and set() before you start mucking with make_accessor().
225
226       make_ro_accessor
227
228           $read_only_accessor = Class->make_ro_accessor($field);
229
230       Generates a subroutine refrence which acts as a read-only accessor for
231       the given $field.  It only calls get().
232
233       Override get() to change the behavior of your accessors.
234
235       make_wo_accessor
236
237           $read_only_accessor = Class->make_wo_accessor($field);
238
239       Generates a subroutine refrence which acts as a write-only accessor
240       (mutator) for the given $field.  It only calls set().
241
242       Override set() to change the behavior of your accessors.
243

EXCEPTIONS

245       If something goes wrong Class::Accessor will warn or die by calling
246       Carp::carp or Carp::croak.  If you don't like this you can override
247       _carp() and _croak() in your subclass and do whatever else you want.
248

EFFICIENCY

250       Class::Accessor does not employ an autoloader, thus it is much faster
251       than you'd think.  Its generated methods incur no special penalty over
252       ones you'd write yourself.
253
254         accessors:
255                      Rate   Basic Average    Fast  Faster  Direct
256         Basic    189150/s      --    -42%    -51%    -55%    -89%
257         Average  327679/s     73%      --    -16%    -22%    -82%
258         Fast     389212/s    106%     19%      --     -8%    -78%
259         Faster   421646/s    123%     29%      8%      --    -76%
260         Direct  1771243/s    836%    441%    355%    320%      --
261
262         mutators:
263                      Rate   Basic Average    Fast  Faster  Direct
264         Basic    173769/s      --    -34%    -53%    -59%    -90%
265         Average  263046/s     51%      --    -29%    -38%    -85%
266         Fast     371158/s    114%     41%      --    -13%    -78%
267         Faster   425821/s    145%     62%     15%      --    -75%
268         Direct  1699081/s    878%    546%    358%    299%      --
269
270       Class::Accessor::Fast is faster than methods written by an average pro‐
271       grammer (where "average" is based on Schwern's example code).
272
273       Class::Accessor is slower than average, but more flexible.
274
275       Class::Accessor::Faster is even faster than Class::Accessor::Fast.  It
276       uses an array internally, not a hash.  This could be a good or bad fea‐
277       ture depending on your point of view.
278
279       Direct hash access is, of course, much faster than all of these, but it
280       provides no encapsulation.
281
282       Of course, its not as simple as saying "Class::Accessor is slower than
283       average".  These are benchmarks for a simple accessor.  If your acces‐
284       sors do any sort of complicated work (such as talking to a database or
285       writing to a file) the time spent doing that work will quickly swamp
286       the time spend just calling the accessor.  In that case, Class::Acces‐
287       sor and the ones you write will be roughly the same speed.
288

EXAMPLES

290       Here's an example of generating an accessor for every public field of
291       your class.
292
293           package Altoids;
294
295           use base qw(Class::Accessor Class::Fields);
296           use fields qw(curiously strong mints);
297           Altoids->mk_accessors( Altoids->show_fields('Public') );
298
299           sub new {
300               my $proto = shift;
301               my $class = ref $proto ⎪⎪ $proto;
302               return fields::new($class);
303           }
304
305           my Altoids $tin = Altoids->new;
306
307           $tin->curiously('Curiouser and curiouser');
308           print $tin->{curiously};    # prints 'Curiouser and curiouser'
309
310           # Subclassing works, too.
311           package Mint::Snuff;
312           use base qw(Altoids);
313
314           my Mint::Snuff $pouch = Mint::Snuff->new;
315           $pouch->strong('Blow your head off!');
316           print $pouch->{strong};     # prints 'Blow your head off!'
317
318       Here's a simple example of altering the behavior of your accessors.
319
320           package Foo;
321           use base qw(Class::Accessor);
322           Foo->mk_accessor(qw(this that up down));
323
324           sub get {
325               my $self = shift;
326
327               # Note every time someone gets some data.
328               print STDERR "Getting @_\n";
329
330               $self->SUPER::get(@_);
331           }
332
333           sub set {
334               my ($self, $key) = splice(@_, 0, 2);
335
336               # Note every time someone sets some data.
337               print STDERR "Setting $key to @_\n";
338
339               $self->SUPER::set($key, @_);
340           }
341

CAVEATS AND TRICKS

343       Class::Accessor has to do some internal wackiness to get its job done
344       quickly and efficiently.  Because of this, there's a few tricks and
345       traps one must know about.
346
347       Hey, nothing's perfect.
348
349       Don't make a field called DESTROY
350
351       This is bad.  Since DESTROY is a magical method it would be bad for us
352       to define an accessor using that name.  Class::Accessor will carp if
353       you try to use it with a field named "DESTROY".
354
355       Overriding autogenerated accessors
356
357       You may want to override the autogenerated accessor with your own, yet
358       have your custom accessor call the default one.  For instance, maybe
359       you want to have an accessor which checks its input.  Normally, one
360       would expect this to work:
361
362           package Foo;
363           use base qw(Class::Accessor);
364           Foo->mk_accessors(qw(email this that whatever));
365
366           # Only accept addresses which look valid.
367           sub email {
368               my($self) = shift;
369               my($email) = @_;
370
371               if( @_ ) {  # Setting
372                   require Email::Valid;
373                   unless( Email::Valid->address($email) ) {
374                       carp("$email doesn't look like a valid address.");
375                       return;
376                   }
377               }
378
379               return $self->SUPER::email(@_);
380           }
381
382       There's a subtle problem in the last example, and its in this line:
383
384           return $self->SUPER::email(@_);
385
386       If we look at how Foo was defined, it called mk_accessors() which stuck
387       email() right into Foo's namespace.  There *is* no SUPER::email() to
388       delegate to!  Two ways around this... first is to make a "pure" base
389       class for Foo.  This pure class will generate the accessors and provide
390       the necessary super class for Foo to use:
391
392           package Pure::Organic::Foo;
393           use base qw(Class::Accessor);
394           Pure::Organic::Foo->mk_accessors(qw(email this that whatever));
395
396           package Foo;
397           use base qw(Pure::Organic::Foo);
398
399       And now Foo::email() can override the generated
400       Pure::Organic::Foo::email() and use it as SUPER::email().
401
402       This is probably the most obvious solution to everyone but me.
403       Instead, what first made sense to me was for mk_accessors() to define
404       an alias of email(), _email_accessor().  Using this solution,
405       Foo::email() would be written with:
406
407           return $self->_email_accessor(@_);
408
409       instead of the expected SUPER::email().
410

AUTHORS

412       Copyright 2007 Marty Pauley <marty+perl@kasei.com>
413
414       This program is free software; you can redistribute it and/or modify it
415       under the same terms as Perl itself.  That means either (a) the GNU
416       General Public License or (b) the Artistic License.
417
418       ORIGINAL AUTHOR
419
420       Michael G Schwern <schwern@pobox.com>
421
422       THANKS
423
424       Liz and RUZ for performance tweaks.
425
426       Tels, for his big feature request/bug report.
427

SEE ALSO

429       Class::Accessor::Fast
430
431       These are some modules which do similar things in different ways
432       Class::Struct, Class::Methodmaker, Class::Generate, Class::Class,
433       Class::Contract
434
435       Class::DBI for an example of this module in use.
436
437
438
439perl v5.8.8                       2007-07-11                Class::Accessor(3)
Impressum