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

NAME

6         Class::Accessor - Automated accessor generation
7

SYNOPSIS

9         package Foo;
10         use base qw(Class::Accessor);
11         Foo->follow_best_practice;
12         Foo->mk_accessors(qw(name role salary));
13
14         # or if you prefer a Moose-like interface...
15
16         package Foo;
17         use Class::Accessor "antlers";
18         has name => ( is => "rw", isa => "Str" );
19         has role => ( is => "rw", isa => "Str" );
20         has salary => ( is => "rw", isa => "Num" );
21
22         # Meanwhile, in a nearby piece of code!
23         # Class::Accessor provides new().
24         my $mp = Foo->new({ name => "Marty", role => "JAPH" });
25
26         my $job = $mp->role;  # gets $mp->{role}
27         $mp->salary(400000);  # sets $mp->{salary} = 400000 # I wish
28
29         # like my @info = @{$mp}{qw(name role)}
30         my @info = $mp->get(qw(name role));
31
32         # $mp->{salary} = 400000
33         $mp->set('salary', 400000);
34

DESCRIPTION

36       This module automagically generates accessors/mutators for your class.
37
38       Most of the time, writing accessors is an exercise in cutting and
39       pasting.  You usually wind up with a series of methods like this:
40
41           sub name {
42               my $self = shift;
43               if(@_) {
44                   $self->{name} = $_[0];
45               }
46               return $self->{name};
47           }
48
49           sub salary {
50               my $self = shift;
51               if(@_) {
52                   $self->{salary} = $_[0];
53               }
54               return $self->{salary};
55           }
56
57         # etc...
58
59       One for each piece of data in your object.  While some will be unique,
60       doing value checks and special storage tricks, most will simply be
61       exercises in repetition.  Not only is it Bad Style to have a bunch of
62       repetitious code, but it's also simply not lazy, which is the real
63       tragedy.
64
65       If you make your module a subclass of Class::Accessor and declare your
66       accessor fields with mk_accessors() then you'll find yourself with a
67       set of automatically generated accessors which can even be customized!
68
69       The basic set up is very simple:
70
71           package Foo;
72           use base qw(Class::Accessor);
73           Foo->mk_accessors( qw(far bar car) );
74
75       Done.  Foo now has simple far(), bar() and car() accessors defined.
76
77       Alternatively, if you want to follow Damian's best practice guidelines
78       you can use:
79
80           package Foo;
81           use base qw(Class::Accessor);
82           Foo->follow_best_practice;
83           Foo->mk_accessors( qw(far bar car) );
84
85       Note: you must call "follow_best_practice" before calling
86       "mk_accessors".
87
88   Moose-like
89       By popular demand we now have a simple Moose-like interface.  You can
90       now do:
91
92           package Foo;
93           use Class::Accessor "antlers";
94           has far => ( is => "rw" );
95           has bar => ( is => "rw" );
96           has car => ( is => "rw" );
97
98       Currently only the "is" attribute is supported.
99

CONSTRUCTOR

101       Class::Accessor provides a basic constructor, "new".  It generates a
102       hash-based object and can be called as either a class method or an
103       object method.
104
105   new
106           my $obj = Foo->new;
107           my $obj = $other_obj->new;
108
109           my $obj = Foo->new(\%fields);
110           my $obj = $other_obj->new(\%fields);
111
112       It takes an optional %fields hash which is used to initialize the
113       object (handy if you use read-only accessors).  The fields of the hash
114       correspond to the names of your accessors, so...
115
116           package Foo;
117           use base qw(Class::Accessor);
118           Foo->mk_accessors('foo');
119
120           my $obj = Foo->new({ foo => 42 });
121           print $obj->foo;    # 42
122
123       however %fields can contain anything, new() will shove them all into
124       your object.
125

MAKING ACCESSORS

127   follow_best_practice
128       In Damian's Perl Best Practices book he recommends separate get and set
129       methods with the prefix set_ and get_ to make it explicit what you
130       intend to do.  If you want to create those accessor methods instead of
131       the default ones, call:
132
133           __PACKAGE__->follow_best_practice
134
135       before you call any of the accessor-making methods.
136
137   accessor_name_for / mutator_name_for
138       You may have your own crazy ideas for the names of the accessors, so
139       you can make those happen by overriding "accessor_name_for" and
140       "mutator_name_for" in your subclass.  (I copied that idea from
141       Class::DBI.)
142
143   mk_accessors
144           __PACKAGE__->mk_accessors(@fields);
145
146       This creates accessor/mutator methods for each named field given in
147       @fields.  Foreach field in @fields it will generate two accessors.  One
148       called "field()" and the other called "_field_accessor()".  For
149       example:
150
151           # Generates foo(), _foo_accessor(), bar() and _bar_accessor().
152           __PACKAGE__->mk_accessors(qw(foo bar));
153
154       See "Overriding autogenerated accessors" in CAVEATS AND TRICKS for
155       details.
156
157   mk_ro_accessors
158         __PACKAGE__->mk_ro_accessors(@read_only_fields);
159
160       Same as mk_accessors() except it will generate read-only accessors (ie.
161       true accessors).  If you attempt to set a value with these accessors it
162       will throw an exception.  It only uses get() and not set().
163
164           package Foo;
165           use base qw(Class::Accessor);
166           Foo->mk_ro_accessors(qw(foo bar));
167
168           # Let's assume we have an object $foo of class Foo...
169           print $foo->foo;  # ok, prints whatever the value of $foo->{foo} is
170           $foo->foo(42);    # BOOM!  Naughty you.
171
172   mk_wo_accessors
173         __PACKAGE__->mk_wo_accessors(@write_only_fields);
174
175       Same as mk_accessors() except it will generate write-only accessors
176       (ie. mutators).  If you attempt to read a value with these accessors it
177       will throw an exception.  It only uses set() and not get().
178
179       NOTE I'm not entirely sure why this is useful, but I'm sure someone
180       will need it.  If you've found a use, let me know.  Right now it's here
181       for orthogonality and because it's easy to implement.
182
183           package Foo;
184           use base qw(Class::Accessor);
185           Foo->mk_wo_accessors(qw(foo bar));
186
187           # Let's assume we have an object $foo of class Foo...
188           $foo->foo(42);      # OK.  Sets $self->{foo} = 42
189           print $foo->foo;    # BOOM!  Can't read from this accessor.
190

Moose!

192       If you prefer a Moose-like interface to create accessors, you can use
193       "has" by importing this module like this:
194
195         use Class::Accessor "antlers";
196
197       or
198
199         use Class::Accessor "moose-like";
200
201       Then you can declare accessors like this:
202
203         has alpha => ( is => "rw", isa => "Str" );
204         has beta  => ( is => "ro", isa => "Str" );
205         has gamma => ( is => "wo", isa => "Str" );
206
207       Currently only the "is" attribute is supported.  And our "is" also
208       supports the "wo" value to make a write-only accessor.
209
210       If you are using the Moose-like interface then you should use the
211       "extends" rather than tweaking your @ISA directly.  Basically, replace
212
213         @ISA = qw/Foo Bar/;
214
215       with
216
217         extends(qw/Foo Bar/);
218

DETAILS

220       An accessor generated by Class::Accessor looks something like this:
221
222           # Your foo may vary.
223           sub foo {
224               my($self) = shift;
225               if(@_) {    # set
226                   return $self->set('foo', @_);
227               }
228               else {
229                   return $self->get('foo');
230               }
231           }
232
233       Very simple.  All it does is determine if you're wanting to set a value
234       or get a value and calls the appropriate method.  Class::Accessor
235       provides default get() and set() methods which your class can override.
236       They're detailed later.
237
238   Modifying the behavior of the accessor
239       Rather than actually modifying the accessor itself, it is much more
240       sensible to simply override the two key methods which the accessor
241       calls.  Namely set() and get().
242
243       If you -really- want to, you can override make_accessor().
244
245   set
246           $obj->set($key, $value);
247           $obj->set($key, @values);
248
249       set() defines how generally one stores data in the object.
250
251       override this method to change how data is stored by your accessors.
252
253   get
254           $value  = $obj->get($key);
255           @values = $obj->get(@keys);
256
257       get() defines how data is retrieved from your objects.
258
259       override this method to change how it is retrieved.
260
261   make_accessor
262           $accessor = __PACKAGE__->make_accessor($field);
263
264       Generates a subroutine reference which acts as an accessor for the
265       given $field.  It calls get() and set().
266
267       If you wish to change the behavior of your accessors, try overriding
268       get() and set() before you start mucking with make_accessor().
269
270   make_ro_accessor
271           $read_only_accessor = __PACKAGE__->make_ro_accessor($field);
272
273       Generates a subroutine reference which acts as a read-only accessor for
274       the given $field.  It only calls get().
275
276       Override get() to change the behavior of your accessors.
277
278   make_wo_accessor
279           $write_only_accessor = __PACKAGE__->make_wo_accessor($field);
280
281       Generates a subroutine reference which acts as a write-only accessor
282       (mutator) for the given $field.  It only calls set().
283
284       Override set() to change the behavior of your accessors.
285

EXCEPTIONS

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

EFFICIENCY

292       Class::Accessor does not employ an autoloader, thus it is much faster
293       than you'd think.  Its generated methods incur no special penalty over
294       ones you'd write yourself.
295
296         accessors:
297                     Rate  Basic   Fast Faster Direct
298         Basic   367589/s     --   -51%   -55%   -89%
299         Fast    747964/s   103%     --    -9%   -77%
300         Faster  819199/s   123%    10%     --   -75%
301         Direct 3245887/s   783%   334%   296%     --
302
303         mutators:
304                     Rate    Acc   Fast Faster Direct
305         Acc     265564/s     --   -54%   -63%   -91%
306         Fast    573439/s   116%     --   -21%   -80%
307         Faster  724710/s   173%    26%     --   -75%
308         Direct 2860979/s   977%   399%   295%     --
309
310       Class::Accessor::Fast is faster than methods written by an average
311       programmer (where "average" is based on Schwern's example code).
312
313       Class::Accessor is slower than average, but more flexible.
314
315       Class::Accessor::Faster is even faster than Class::Accessor::Fast.  It
316       uses an array internally, not a hash.  This could be a good or bad
317       feature depending on your point of view.
318
319       Direct hash access is, of course, much faster than all of these, but it
320       provides no encapsulation.
321
322       Of course, it's not as simple as saying "Class::Accessor is slower than
323       average".  These are benchmarks for a simple accessor.  If your
324       accessors do any sort of complicated work (such as talking to a
325       database or writing to a file) the time spent doing that work will
326       quickly swamp the time spend just calling the accessor.  In that case,
327       Class::Accessor and the ones you write will be roughly the same speed.
328

EXAMPLES

330       Here's an example of generating an accessor for every public field of
331       your class.
332
333           package Altoids;
334
335           use base qw(Class::Accessor Class::Fields);
336           use fields qw(curiously strong mints);
337           Altoids->mk_accessors( Altoids->show_fields('Public') );
338
339           sub new {
340               my $proto = shift;
341               my $class = ref $proto || $proto;
342               return fields::new($class);
343           }
344
345           my Altoids $tin = Altoids->new;
346
347           $tin->curiously('Curiouser and curiouser');
348           print $tin->{curiously};    # prints 'Curiouser and curiouser'
349
350
351           # Subclassing works, too.
352           package Mint::Snuff;
353           use base qw(Altoids);
354
355           my Mint::Snuff $pouch = Mint::Snuff->new;
356           $pouch->strong('Blow your head off!');
357           print $pouch->{strong};     # prints 'Blow your head off!'
358
359       Here's a simple example of altering the behavior of your accessors.
360
361           package Foo;
362           use base qw(Class::Accessor);
363           Foo->mk_accessors(qw(this that up down));
364
365           sub get {
366               my $self = shift;
367
368               # Note every time someone gets some data.
369               print STDERR "Getting @_\n";
370
371               $self->SUPER::get(@_);
372           }
373
374           sub set {
375               my ($self, $key) = splice(@_, 0, 2);
376
377               # Note every time someone sets some data.
378               print STDERR "Setting $key to @_\n";
379
380               $self->SUPER::set($key, @_);
381           }
382

CAVEATS AND TRICKS

384       Class::Accessor has to do some internal wackiness to get its job done
385       quickly and efficiently.  Because of this, there's a few tricks and
386       traps one must know about.
387
388       Hey, nothing's perfect.
389
390   Don't make a field called DESTROY
391       This is bad.  Since DESTROY is a magical method it would be bad for us
392       to define an accessor using that name.  Class::Accessor will carp if
393       you try to use it with a field named "DESTROY".
394
395   Overriding autogenerated accessors
396       You may want to override the autogenerated accessor with your own, yet
397       have your custom accessor call the default one.  For instance, maybe
398       you want to have an accessor which checks its input.  Normally, one
399       would expect this to work:
400
401           package Foo;
402           use base qw(Class::Accessor);
403           Foo->mk_accessors(qw(email this that whatever));
404
405           # Only accept addresses which look valid.
406           sub email {
407               my($self) = shift;
408               my($email) = @_;
409
410               if( @_ ) {  # Setting
411                   require Email::Valid;
412                   unless( Email::Valid->address($email) ) {
413                       carp("$email doesn't look like a valid address.");
414                       return;
415                   }
416               }
417
418               return $self->SUPER::email(@_);
419           }
420
421       There's a subtle problem in the last example, and it's in this line:
422
423           return $self->SUPER::email(@_);
424
425       If we look at how Foo was defined, it called mk_accessors() which stuck
426       email() right into Foo's namespace.  There *is* no SUPER::email() to
427       delegate to!  Two ways around this... first is to make a "pure" base
428       class for Foo.  This pure class will generate the accessors and provide
429       the necessary super class for Foo to use:
430
431           package Pure::Organic::Foo;
432           use base qw(Class::Accessor);
433           Pure::Organic::Foo->mk_accessors(qw(email this that whatever));
434
435           package Foo;
436           use base qw(Pure::Organic::Foo);
437
438       And now Foo::email() can override the generated
439       Pure::Organic::Foo::email() and use it as SUPER::email().
440
441       This is probably the most obvious solution to everyone but me.
442       Instead, what first made sense to me was for mk_accessors() to define
443       an alias of email(), _email_accessor().  Using this solution,
444       Foo::email() would be written with:
445
446           return $self->_email_accessor(@_);
447
448       instead of the expected SUPER::email().
449

AUTHORS

451       Copyright 2017 Marty Pauley <marty+perl@martian.org>
452
453       This program is free software; you can redistribute it and/or modify it
454       under the same terms as Perl itself.  That means either (a) the GNU
455       General Public License or (b) the Artistic License.
456
457   ORIGINAL AUTHOR
458       Michael G Schwern <schwern@pobox.com>
459
460   THANKS
461       Liz and RUZ for performance tweaks.
462
463       Tels, for his big feature request/bug report.
464
465       Various presenters at YAPC::Asia 2009 for criticising the non-Moose
466       interface.
467

SEE ALSO

469       See Class::Accessor::Fast and Class::Accessor::Faster if speed is more
470       important than flexibility.
471
472       These are some modules which do similar things in different ways
473       Class::Struct, Class::Methodmaker, Class::Generate, Class::Class,
474       Class::Contract, Moose, Mouse
475
476       See Class::DBI for an example of this module in use.
477
478
479
480perl v5.28.0                      2017-10-22                Class::Accessor(3)
Impressum