Manual Pages for UNIX Darwin command on man Class::Accessor
MyWebUniversity

Manual Pages for UNIX Darwin command on man Class::Accessor

Class::Accessor(3) User Contributed Perl Documentation Class::Accessor(3)

NAME

Class::Accessor - Automated accessor generation

SYNOPSIS

package Employee;

use base qw(Class::Accessor);

Employee->mkaccessors(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);

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 mkaccessors() 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->mkaccessors( qw(foo bar car) );

Done. My::Class now has simple foo(), bar() and car() accessors defined. WWhhaatt MMaakkeess TThhiiss DDiiffffeerreenntt?? What makes this module special compared to all the other method

generating modules ("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. MMEETTHHOODDSS nneeww

my $obj = Class->new;

my $obj = $otherobj->new;

my $obj = Class->new(\%fields);

my $obj = $otherobj->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

correspond to the names of your accessors, so... package Foo;

use base qw(Class::Accessor);

Foo->mkaccessors('foo');

my $obj = Class->new({ foo => 42 });

print $obj->foo; # 42

however %fields can contain anything, new() will shove them all into

your object. Don't like it? Override it. mmkkaacccceessssoorrss

Class->mkaccessors(@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 "fieldaccessor()". For example:

# Generates foo(), fooaccessor(), bar() and baraccessor().

Class->mkaccessors(qw(foo bar));

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

Class->mkroaccessors(@readonlyfields);

Same as mkaccessors() except it will generate read-only accessors (ie.

true accessors). If you attempt to set a value with these accessors it will throw an exception. It only uses get() and not set(). package Foo;

use base qw(Class::Accessor);

Class->mkroaccessors(qw(foo bar));

# Let's assume we have an object $foo of class Foo...

print $foo->foo; # ok, prints whatever the value of $foo->{foo} is

$foo->foo(42); # BOOM! Naughty you.

mmkkwwooaacccceessssoorrss

Class->mkwoaccessors(@writeonlyfields);

Same as mkaccessors() except it will generate write-only accessors

(ie. mutators). If you attempt to read a value with these accessors it will throw an exception. It only uses set() and not get(). NNOOTTEE I'm not entirely sure why this is useful, but I'm sure someone will need it. If you've found a use, let me know. Right now its here for orthoginality and because its easy to implement. package Foo;

use base qw(Class::Accessor);

Class->mkwoaccessors(qw(foo bar));

# Let's assume we have an object $foo of class Foo...

$foo->foo(42); # OK. Sets $self->{foo} = 42

print $foo->foo; # BOOM! Can't read from this accessor.

DDEETTAAIILLSS

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. ffoolllloowwbbeessttpprraaccttiiccee In Damian's Perl Best Practices book he recommends separate get and set methods with the prefix set and get to make it explicit what you intend to do. If you want to create those accessor methods instead of the default ones, call:

PACKAGE->followbestpractice

aacccceessssoorrnnaammeeffoorr // mmuuttaattoorrnnaammeeffoorr You may have your own crazy ideas for the names of the accessors, so you can make those happen by overriding "accessornamefor" and "mutatornamefor" in your subclass. (I copied that idea from Class::DBI.) MMooddiiffyyiinngg tthhee bbeehhaavviioorr ooff tthhee aacccceessssoorr 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 makeaccessor().

sseett

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

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

set() defines how generally one stores data in the object. override this method to change how data is stored by your accessors. ggeett

$value = $obj->get($key);

@values = $obj->get(@keys);

get() defines how data is retreived from your objects. override this method to change how it is retreived. mmaakkeeaacccceessssoorr

$accessor = Class->makeaccessor($field);

Generates a subroutine reference which acts as an accessor for the

given $field. It calls get() and set().

If you wish to change the behavior of your accessors, try overriding get() and set() before you start mucking with makeaccessor(). mmaakkeerrooaacccceessssoorr

$readonlyaccessor = Class->makeroaccessor($field);

Generates a subroutine refrence which acts as a read-only accessor for

the given $field. It only calls get().

Override get() to change the behavior of your accessors. mmaakkeewwooaacccceessssoorr

$readonlyaccessor = Class->makewoaccessor($field);

Generates a subroutine refrence which acts as a write-only accessor

(mutator) for the given $field. It only calls set().

Override set() to change the behavior of your accessors. EEXXCCEEPPTTIIOONNSS

If something goes wrong Class::Accessor will warn or die by calling

Carp::carp or Carp::croak. If you don't like this you can override carp() and croak() in your subclass and do whatever else you want. EEFFFFIICCIIEENNCCYY

Class::Accessor does not employ an autoloader, thus it is much faster

than you'd think. Its generated methods incur no special penalty over ones you'd write yourself.

Here are Schwern's results of benchmarking Class::Accessor,

Class::Accessor::Fast, a hand-written accessor, and direct hash access.

Benchmark: timing 500000 iterations of By Hand - get, By Hand - set,

C::A - get, C::A - set, C::A::Fast - get, C::A::Fast - set,

Direct - get, Direct - set...

By Hand - get: 4 wallclock secs ( 5.09 usr + 0.00 sys = 5.09 CPU)

@ 98231.83/s (n=500000)

By Hand - set: 5 wallclock secs ( 6.06 usr + 0.00 sys = 6.06 CPU)

@ 82508.25/s (n=500000)

C::A - get: 9 wallclock secs ( 9.83 usr + 0.01 sys = 9.84 CPU)

@ 50813.01/s (n=500000)

C::A - set: 11 wallclock secs ( 9.95 usr + 0.00 sys = 9.95 CPU)

@ 50251.26/s (n=500000)

C::A::Fast - get: 6 wallclock secs ( 4.88 usr + 0.00 sys = 4.88 CPU)

@ 102459.02/s (n=500000)

C::A::Fast - set: 6 wallclock secs ( 5.83 usr + 0.00 sys = 5.83 CPU)

@ 85763.29/s (n=500000)

Direct - get: 0 wallclock secs ( 0.89 usr + 0.00 sys = 0.89 CPU)

@ 561797.75/s (n=500000)

Direct - set: 2 wallclock secs ( 0.87 usr + 0.00 sys = 0.87 CPU)

@ 574712.64/s (n=500000)

So Class::Accessor::Fast is just as fast as one you'd write yourself

while Class::Accessor is twice as slow, a price paid for flexibility.

Direct hash access is about six times faster, but provides no encapsulation and no flexibility.

Of course, its not as simple as saying "Class::Accessor is twice as

slow as one you write yourself". These are benchmarks for the simplest possible accessor, if your accessors do any sort of complicated work (such as talking to a database or writing to a file) the time spent doing that work will quickly swamp the time spend just calling the

accessor. In that case, Class::Accessor and the ones you write will

tend to be just as fast. EEXXAAMMPPLLEESS Here's an example of generating an accessor for every public field of your class. package Altoids;

use base qw(Class::Accessor Class::Fields);

use fields qw(curiously strong mints);

Altoids->mkaccessors( Altoids->showfields('Public') );

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('Blow your head off!');

print $pouch->{strong}; # prints 'Blow your head off!'

Here's a simple example of altering the behavior of your accessors. package Foo;

use base qw(Class::Accessor);

Foo->mkaccessor(qw(this that up down));

sub get {

my $self = shift;

# Note every time someone gets some data.

print STDERR "Getting @\n";

$self->SUPER::get(@);

} sub set {

my ($self, $key) = splice(@, 0, 2);

# Note every time someone sets some data.

print STDERR "Setting $key to @\n";

$self->SUPER::set($key, @);

} CCAAVVEEAATTSS AANNDD TTRRIICCKKSS

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. DDoonn''tt mmaakkee aa ffiieelldd ccaalllleedd DDEESSTTRROOYY 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". OOvveerrrriiddiinngg aauuttooggeenneerraatteedd aacccceessssoorrss 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->mkaccessors(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 mkaccessors() 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->mkaccessors(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 mkaccessors() to define an alias of email(), emailaccessor(). Using this solution, Foo::email() would be written with:

return $self->emailaccessor(@);

instead of the expected SUPER::email(). AUTHORS Copyright 2005 Marty Pauley This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. That means either (a) the GNU General Public License or (b) the Artistic License. ORIGINAL AUTHOR Michael G Schwern TTHHAANNKKSS Liz, for performance tweaks. Tels, for his big feature request/bug report.

SEE ALSO

Class::Accessor::Fast

These are some modules which do similar things in different ways Class::Struct, Class::Methodmaker, Class::Generate, Class::Class, Class::Contract Class::DBI for an example of this module in use.

perl v5.8.8 2006-11-25 Class::Accessor(3)




Contact us      |      About us      |      Term of use      |       Copyright © 2000-2019 MyWebUniversity.com ™