1Class::Accessor(3) User Contributed Perl Documentation Class::Accessor(3)
2
3
4
6 Class::Accessor - Automated accessor generation
7
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
27 This module automagically generates accessors/mutators for your class.
28
29 Most of the time, writing accessors is an exercise in cutting and
30 pasting. 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 What makes this module special compared to all the other method
71 generating modules ("SEE ALSO")? By overriding the get() and set()
72 methods you can alter the behavior of the accessors class-wide. Also,
73 the accessors are implemented as closures which should cost a bit less
74 memory than most other solutions which generate a new method for each
75 accessor.
76
78 new
79 my $obj = Class->new;
80 my $obj = $other_obj->new;
81
82 my $obj = Class->new(\%fields);
83 my $obj = $other_obj->new(\%fields);
84
85 Class::Accessor provides a basic constructor. It generates a hash-
86 based object and can be called as either a class method or an object
87 method.
88
89 It takes an optional %fields hash which is used to initialize the
90 object (handy if you use read-only accessors). The fields of the hash
91 correspond to the names of your accessors, so...
92
93 package Foo;
94 use base qw(Class::Accessor);
95 Foo->mk_accessors('foo');
96
97 my $obj = Class->new({ foo => 42 });
98 print $obj->foo; # 42
99
100 however %fields can contain anything, new() will shove them all into
101 your object. Don't like it? Override it.
102
103 mk_accessors
104 Class->mk_accessors(@fields);
105
106 This creates accessor/mutator methods for each named field given in
107 @fields. Foreach field in @fields it will generate two accessors. One
108 called "field()" and the other called "_field_accessor()". For
109 example:
110
111 # Generates foo(), _foo_accessor(), bar() and _bar_accessor().
112 Class->mk_accessors(qw(foo bar));
113
114 See "Overriding autogenerated accessors" in CAVEATS AND TRICKS for
115 details.
116
117 mk_ro_accessors
118 Class->mk_ro_accessors(@read_only_fields);
119
120 Same as mk_accessors() except it will generate read-only accessors (ie.
121 true accessors). If you attempt to set a value with these accessors it
122 will throw an exception. It only uses get() and not set().
123
124 package Foo;
125 use base qw(Class::Accessor);
126 Class->mk_ro_accessors(qw(foo bar));
127
128 # Let's assume we have an object $foo of class Foo...
129 print $foo->foo; # ok, prints whatever the value of $foo->{foo} is
130 $foo->foo(42); # BOOM! Naughty you.
131
132 mk_wo_accessors
133 Class->mk_wo_accessors(@write_only_fields);
134
135 Same as mk_accessors() except it will generate write-only accessors
136 (ie. mutators). If you attempt to read a value with these accessors it
137 will throw an exception. It only uses set() and not get().
138
139 NOTE I'm not entirely sure why this is useful, but I'm sure someone
140 will need it. If you've found a use, let me know. Right now its here
141 for orthoginality and because its easy to implement.
142
143 package Foo;
144 use base qw(Class::Accessor);
145 Class->mk_wo_accessors(qw(foo bar));
146
147 # Let's assume we have an object $foo of class Foo...
148 $foo->foo(42); # OK. Sets $self->{foo} = 42
149 print $foo->foo; # BOOM! Can't read from this accessor.
150
152 An accessor generated by Class::Accessor looks something like this:
153
154 # Your foo may vary.
155 sub foo {
156 my($self) = shift;
157 if(@_) { # set
158 return $self->set('foo', @_);
159 }
160 else {
161 return $self->get('foo');
162 }
163 }
164
165 Very simple. All it does is determine if you're wanting to set a value
166 or get a value and calls the appropriate method. Class::Accessor
167 provides default get() and set() methods which your class can override.
168 They're detailed later.
169
170 follow_best_practice
171 In Damian's Perl Best Practices book he recommends separate get and set
172 methods with the prefix set_ and get_ to make it explicit what you
173 intend to do. If you want to create those accessor methods instead of
174 the default ones, call:
175
176 __PACKAGE__->follow_best_practice
177
178 accessor_name_for / mutator_name_for
179 You may have your own crazy ideas for the names of the accessors, so
180 you can make those happen by overriding "accessor_name_for" and
181 "mutator_name_for" in your subclass. (I copied that idea from
182 Class::DBI.)
183
184 Modifying the behavior of the accessor
185 Rather than actually modifying the accessor itself, it is much more
186 sensible to simply override the two key methods which the accessor
187 calls. Namely set() and get().
188
189 If you -really- want to, you can override make_accessor().
190
191 set
192 $obj->set($key, $value);
193 $obj->set($key, @values);
194
195 set() defines how generally one stores data in the object.
196
197 override this method to change how data is stored by your accessors.
198
199 get
200 $value = $obj->get($key);
201 @values = $obj->get(@keys);
202
203 get() defines how data is retreived from your objects.
204
205 override this method to change how it is retreived.
206
207 make_accessor
208 $accessor = Class->make_accessor($field);
209
210 Generates a subroutine reference which acts as an accessor for the
211 given $field. It calls get() and set().
212
213 If you wish to change the behavior of your accessors, try overriding
214 get() and set() before you start mucking with make_accessor().
215
216 make_ro_accessor
217 $read_only_accessor = Class->make_ro_accessor($field);
218
219 Generates a subroutine refrence which acts as a read-only accessor for
220 the given $field. It only calls get().
221
222 Override get() to change the behavior of your accessors.
223
224 make_wo_accessor
225 $read_only_accessor = Class->make_wo_accessor($field);
226
227 Generates a subroutine refrence which acts as a write-only accessor
228 (mutator) for the given $field. It only calls set().
229
230 Override set() to change the behavior of your accessors.
231
233 If something goes wrong Class::Accessor will warn or die by calling
234 Carp::carp or Carp::croak. If you don't like this you can override
235 _carp() and _croak() in your subclass and do whatever else you want.
236
238 Class::Accessor does not employ an autoloader, thus it is much faster
239 than you'd think. Its generated methods incur no special penalty over
240 ones you'd write yourself.
241
242 accessors:
243 Rate Basic Average Fast Faster Direct
244 Basic 189150/s -- -42% -51% -55% -89%
245 Average 327679/s 73% -- -16% -22% -82%
246 Fast 389212/s 106% 19% -- -8% -78%
247 Faster 421646/s 123% 29% 8% -- -76%
248 Direct 1771243/s 836% 441% 355% 320% --
249
250 mutators:
251 Rate Basic Average Fast Faster Direct
252 Basic 173769/s -- -34% -53% -59% -90%
253 Average 263046/s 51% -- -29% -38% -85%
254 Fast 371158/s 114% 41% -- -13% -78%
255 Faster 425821/s 145% 62% 15% -- -75%
256 Direct 1699081/s 878% 546% 358% 299% --
257
258 Class::Accessor::Fast is faster than methods written by an average
259 programmer (where "average" is based on Schwern's example code).
260
261 Class::Accessor is slower than average, but more flexible.
262
263 Class::Accessor::Faster is even faster than Class::Accessor::Fast. It
264 uses an array internally, not a hash. This could be a good or bad
265 feature depending on your point of view.
266
267 Direct hash access is, of course, much faster than all of these, but it
268 provides no encapsulation.
269
270 Of course, its not as simple as saying "Class::Accessor is slower than
271 average". These are benchmarks for a simple accessor. If your
272 accessors do any sort of complicated work (such as talking to a
273 database or writing to a file) the time spent doing that work will
274 quickly swamp the time spend just calling the accessor. In that case,
275 Class::Accessor and the ones you write will be roughly the same speed.
276
278 Here's an example of generating an accessor for every public field of
279 your class.
280
281 package Altoids;
282
283 use base qw(Class::Accessor Class::Fields);
284 use fields qw(curiously strong mints);
285 Altoids->mk_accessors( Altoids->show_fields('Public') );
286
287 sub new {
288 my $proto = shift;
289 my $class = ref $proto || $proto;
290 return fields::new($class);
291 }
292
293 my Altoids $tin = Altoids->new;
294
295 $tin->curiously('Curiouser and curiouser');
296 print $tin->{curiously}; # prints 'Curiouser and curiouser'
297
298
299 # Subclassing works, too.
300 package Mint::Snuff;
301 use base qw(Altoids);
302
303 my Mint::Snuff $pouch = Mint::Snuff->new;
304 $pouch->strong('Blow your head off!');
305 print $pouch->{strong}; # prints 'Blow your head off!'
306
307 Here's a simple example of altering the behavior of your accessors.
308
309 package Foo;
310 use base qw(Class::Accessor);
311 Foo->mk_accessor(qw(this that up down));
312
313 sub get {
314 my $self = shift;
315
316 # Note every time someone gets some data.
317 print STDERR "Getting @_\n";
318
319 $self->SUPER::get(@_);
320 }
321
322 sub set {
323 my ($self, $key) = splice(@_, 0, 2);
324
325 # Note every time someone sets some data.
326 print STDERR "Setting $key to @_\n";
327
328 $self->SUPER::set($key, @_);
329 }
330
332 Class::Accessor has to do some internal wackiness to get its job done
333 quickly and efficiently. Because of this, there's a few tricks and
334 traps one must know about.
335
336 Hey, nothing's perfect.
337
338 Don't make a field called DESTROY
339 This is bad. Since DESTROY is a magical method it would be bad for us
340 to define an accessor using that name. Class::Accessor will carp if
341 you try to use it with a field named "DESTROY".
342
343 Overriding autogenerated accessors
344 You may want to override the autogenerated accessor with your own, yet
345 have your custom accessor call the default one. For instance, maybe
346 you want to have an accessor which checks its input. Normally, one
347 would expect this to work:
348
349 package Foo;
350 use base qw(Class::Accessor);
351 Foo->mk_accessors(qw(email this that whatever));
352
353 # Only accept addresses which look valid.
354 sub email {
355 my($self) = shift;
356 my($email) = @_;
357
358 if( @_ ) { # Setting
359 require Email::Valid;
360 unless( Email::Valid->address($email) ) {
361 carp("$email doesn't look like a valid address.");
362 return;
363 }
364 }
365
366 return $self->SUPER::email(@_);
367 }
368
369 There's a subtle problem in the last example, and its in this line:
370
371 return $self->SUPER::email(@_);
372
373 If we look at how Foo was defined, it called mk_accessors() which stuck
374 email() right into Foo's namespace. There *is* no SUPER::email() to
375 delegate to! Two ways around this... first is to make a "pure" base
376 class for Foo. This pure class will generate the accessors and provide
377 the necessary super class for Foo to use:
378
379 package Pure::Organic::Foo;
380 use base qw(Class::Accessor);
381 Pure::Organic::Foo->mk_accessors(qw(email this that whatever));
382
383 package Foo;
384 use base qw(Pure::Organic::Foo);
385
386 And now Foo::email() can override the generated
387 Pure::Organic::Foo::email() and use it as SUPER::email().
388
389 This is probably the most obvious solution to everyone but me.
390 Instead, what first made sense to me was for mk_accessors() to define
391 an alias of email(), _email_accessor(). Using this solution,
392 Foo::email() would be written with:
393
394 return $self->_email_accessor(@_);
395
396 instead of the expected SUPER::email().
397
399 Copyright 2007 Marty Pauley <marty+perl@kasei.com>
400
401 This program is free software; you can redistribute it and/or modify it
402 under the same terms as Perl itself. That means either (a) the GNU
403 General Public License or (b) the Artistic License.
404
405 ORIGINAL AUTHOR
406 Michael G Schwern <schwern@pobox.com>
407
408 THANKS
409 Liz and RUZ for performance tweaks.
410
411 Tels, for his big feature request/bug report.
412
414 Class::Accessor::Fast
415
416 These are some modules which do similar things in different ways
417 Class::Struct, Class::Methodmaker, Class::Generate, Class::Class,
418 Class::Contract
419
420 Class::DBI for an example of this module in use.
421
422
423
424perl v5.10.1 2007-07-11 Class::Accessor(3)