Class::Accessor::Chained - make chained accessors


Class-Accessor-Chained documentation Contained in the Class-Accessor-Chained distribution.

Index


Code Index:

NAME

Top

Class::Accessor::Chained - make chained accessors

SYNOPSIS

Top

 package Foo;
 use base qw( Class::Accessor::Chained );
 __PACKAGE__->mk_accessors(qw( foo bar baz ));

 my $foo = Foo->new->foo(1)->bar(2)->baz(4);
 print $foo->bar; # prints 2

DESCRIPTION

Top

A chained accessor is one that always returns the object when called with parameters (to set), and the value of the field when called with no arguments.

This module subclasses Class::Accessor in order to provide the same mk_accessors interface.

AUTHOR

Top

Richard Clamp <richardc@unixbeard.net>

COPYRIGHT

Top

SEE ALSO

Top

Class::Accessor, Class::Accessor::Chained::Fast


Class-Accessor-Chained documentation Contained in the Class-Accessor-Chained distribution.

use strict;
package Class::Accessor::Chained;
use base 'Class::Accessor';
our $VERSION = '0.01';

sub make_accessor {
    my($class, $field) = @_;

    # Build a closure around $field.
    return sub {
        my($self) = shift;

        if (@_) {
            $self->set($field, @_);
            return $self;
        }
        else {
            return $self->get($field);
        }
    };
}

sub make_wo_accessor {
    my($class, $field) = @_;

    return sub {
        my($self) = shift;

        unless (@_) {
            my $caller = caller;
            require Carp;
            Carp::croak("'$caller' cannot access the value of '$field' on ".
                        "objects of class '$class'");
        }
        else {
            $self->set($field, @_);
            return $self;
        }
    };
}

1;
__END__