13 June 2006

Perl's Class::Accessor

If you find yourself writing a Perl module for a class with a large number of attributes and a correspondingly large number of accessors and mutators ('getters' and 'setters'), you might want to try Class::Accessor. With Class::Accessor as a base class, your module can just declare its attributes, and Class::Accessor will generate all the accessors and mutators (and the constructor) automatically.

(Your Perl distribution may not include Class::Accessor, in which case you'd need to install it from CPAN.)

Here's an example of how you might use Class::Accessor:

package MyPerson;
use base qw/ Class::Accessor /;
MyPerson->mk_accessors(
qw/
fname
mname
lname
birthdate
address
/
);

1;

Then in your Perl program:

use MyPerson;

my $person = MyPerson->new(
{
fname => 'Homer',
mname => 'Jay',
lname => 'Simpson',
birthdate => '1 January 1970',
}
);

my $birthdate = $person->birthdate(); # $birthdate is now '1 January 1970'
$person->address('742 Evergreen Terrace, Springfield'); # sets the address attribute


Note that you didn't have to explicitly write a constructor--your code just gives new() a hashref of the attributes you want to set.

You can now even use MyPerson as a base class. Another package can inherit from MyPerson and add its own attributes:

package MyCustomer;
use base qw/ MyPerson /;
MyCustomer->mk_accessors(
qw/
billing_address
shipping_address
/
);

1;


The documentation for Class::Accessor is worth reading--it offers ways to declare read-only and write-only attributes (the former would only have accessors, and the latter would only have mutators).

No comments: