NAME

Class::Accessor - Automated accessor generation

SYNOPSIS

package Foo;

use base qw(Class::Accessor);
Foo->mk_accessors(qw(this that whatever));

sub new { return bless {} }

# Meanwhile, in a nearby piece of code!
my $foo = Foo->new;

my $whatever = $foo->whatever;    # gets $foo->{whatever}
$foo->this('likmi');              # sets $foo->{this} = 'likmi'

# Similar to @values = @{$foo}{qw(that whatever)}
@values = $foo->get(qw(that whatever));

# sets $foo->{that} = 'crazy thing'
$foo->set('that', 'crazy thing');

DESCRIPTION

This module automagically generates accessor/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:

# accessor for $obj->{foo}
sub foo {
    my($self) = shift;

    if(@_ == 1) {
        $self->{foo} = shift;
    }
    elsif(@_ > 1) {
        $self->{foo} = [@_];
    }

    return $self->{foo};
}
        

# accessor for $obj->{bar}
sub bar {
    my($self) = shift;

    if(@_ == 1) {
        $self->{bar} = shift;
    }
    elsif(@_ > 1) {
        $self->{bar} = [@_];
    }

    return $self->{bar};
}

# 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.

mk_accessors
Class->mk_accessors(@fields);

This creates accessor/mutator methods for each named field given in @fields. Foreach field in @fields it will generate two accessors. One called "field()" and the other called "_field_accessor()". For example:

# Generates foo(), _foo_accessor(), bar() and _bar_accessor().
Class->mk_accessors(qw(foo bar));

See "Overriding autogenerated accessors" in CAVEATS AND TRICKS for details.

The rest is details.

DETAILS

An accessor generated by Class::Accessor looks something like this:

# Your foo may vary.
sub foo {
    my($self) = shift;
    if(@_) {    # set
        return $self->set('foo', @_);
    }
    else {
        return $self->get('foo');
    }
}

Very simple. All it does is determine if you're wanting to set a value or get a value and calls the appropriate method. Class::Accessor provides default get() and set() methods which your class can override. They're detailed later.

Modifying the behavior of the accessor

Rather than actually modifying the accessor itself, it is much more sensible to simply override the two key methods which the accessor calls. Namely set() and get().

If you -really- want to, you can override make_accessor().

set
$obj->set($key, $value);
$obj->set($key, @values);

set() defines how generally one stores data in the object.

get
$value  = $obj->get($key);
@values = $obj->get(@keys);
make_accessor
$accessor = Class->make_accessor($field);

Generates a subroutine reference which acts as an accessor for the given $field.

EXAMPLES

Here's an example of generating an accessor for every public field of your class.

package Altoids;

use base qw(Class::Accessor);
use fields qw(curiously strong mints);
Altoids->mk_accessors(keys %Altoids::FIELDS);

sub new {
    my $proto = shift;
    my $class = ref $proto || $proto;
    return fields::new($class);
}

my Altoids $tin = Altoids->new;

$tin->curiously('Curiouser and curiouser');
print $tin->{curiously};    # prints 'Curiouser and curiouser'


# Subclassing works, too.
package Mint::Snuff;
use base qw(Altoids);

my Mint::Snuff $pouch = Mint::Snuff->new;
$pouch->strong('Fuck you up strong!');
print $pouch->{strong};     # prints 'Fuck you up strong!'

CAVEATS AND TRICKS

Class::Accessor has to do some internal wackiness to get its job done quickly and efficiently. Because of this, there's a few tricks and traps one must know about.

Hey, nothing's perfect.

Don't make a field called DESTROY

This is bad. Since DESTROY is a magical method it would be bad for us to define an accessor using that name. Class::Accessor will carp if you try to use it with a field named "DESTROY".

Overriding autogenerated accessors

You may want to override the autogenerated accessor with your own, yet have your custom accessor call the default one. For instance, maybe you want to have an accessor which checks its input. Normally, one would expect this to work:

package Foo;
use base qw(Class::Accessor);
Foo->mk_accessors(qw(email this that whatever));

# Only accept addresses which look valid.
sub email {
    my($self) = shift;
    my($email) = @_;

    if( @_ ) {  # Setting
        require Email::Valid;
        unless( Email::Valid->address($email) ) {
            carp("$email doesn't look like a valid address.");
            return;
        }
    }

    return $self->SUPER::email(@_);
}

There's a subtle problem in the last example, and its in this line:

return $self->SUPER::email(@_);

If we look at how Foo was defined, it called mk_accessors() which stuck email() right into Foo's namespace. There *is* no SUPER::email() to delegate to! Two ways around this... first is to make a "pure" base class for Foo. This pure class will generate the accessors and provide the necessary super class for Foo to use:

package Pure::Organic::Foo;
use base qw(Class::Accessor);
Pure::Organic::Foo->mk_accessors(qw(email this that whatever));

package Foo;
use base qw(Pure::Organic::Foo);

And now Foo::email() can override the generated Pure::Organic::Foo::email() and use it as SUPER::email().

This is probably the most obvious solution to everyone but me. Instead, what first made sense to me was for mk_accessors() to define an alias of email(), _email_accessor(). Using this solution, Foo::email() would be written with:

return $self->_email_accessor(@_);

instead of the expected SUPER::email().

AUTHOR

Michael G Schwern <schwern@pobox.com>