package Class::Accessor;
require 5.00502;
use strict;
$Class::Accessor::VERSION = '0.31';
=head1 NAME
Class::Accessor - Automated accessor generation
=head1 SYNOPSIS
package Employee;
use base qw(Class::Accessor);
Employee->mk_accessors(qw(name role salary));
# Meanwhile, in a nearby piece of code!
# Class::Accessor provides new().
my $mp = Foo->new({ name => "Marty", role => "JAPH" });
my $job = $mp->role; # gets $mp->{role}
$mp->salary(400000); # sets $mp->{salary} = 400000 (I wish)
# like my @info = @{$mp}{qw(name role)}
my @info = $mp->get(qw(name role));
# $mp->{salary} = 400000
$mp->set('salary', 400000);
=head1 DESCRIPTION
This module automagically generates accessors/mutators for your class.
Most of the time, writing accessors is an exercise in cutting and
pasting. You usually wind up with a series of methods like this:
sub name {
my $self = shift;
if(@_) {
$self->{name} = $_[0];
}
return $self->{name};
}
sub salary {
my $self = shift;
if(@_) {
$self->{salary} = $_[0];
}
return $self->{salary};
}
# etc...
One for each piece of data in your object. While some will be unique,
doing value checks and special storage tricks, most will simply be
exercises in repetition. Not only is it Bad Style to have a bunch of
repetitious code, but its also simply not lazy, which is the real
tragedy.
If you make your module a subclass of Class::Accessor and declare your
accessor fields with mk_accessors() then you'll find yourself with a
set of automatically generated accessors which can even be
customized!
The basic set up is very simple:
package My::Class;
use base qw(Class::Accessor);
My::Class->mk_accessors( qw(foo bar car) );
Done. My::Class now has simple foo(), bar() and car() accessors
defined.
=head2 What Makes This Different?
What makes this module special compared to all the other method
generating modules (L<"SEE ALSO">)? By overriding the get() and set()
methods you can alter the behavior of the accessors class-wide. Also,
the accessors are implemented as closures which should cost a bit less
memory than most other solutions which generate a new method for each
accessor.
=head1 METHODS
=head2 new
my $obj = Class->new;
my $obj = $other_obj->new;
my $obj = Class->new(\%fields);
my $obj = $other_obj->new(\%fields);
Class::Accessor provides a basic constructor. It generates a
hash-based object and can be called as either a class method or an
object method.
It takes an optional %fields hash which is used to initialize the
object (handy if you use read-only accessors). The fields of the hash
=1= |