Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

Tools

Object::Accessor

Perl 5 version 10.1 documentation
Recently read

Object::Accessor

NAME

Object::Accessor

SYNOPSIS

  1. ### using the object
  2. $obj = Object::Accessor->new; # create object
  3. $obj = Object::Accessor->new(@list); # create object with accessors
  4. $obj = Object::Accessor->new(\%h); # create object with accessors
  5. # and their allow handlers
  6. $bool = $obj->mk_accessors('foo'); # create accessors
  7. $bool = $obj->mk_accessors( # create accessors with input
  8. {foo => ALLOW_HANDLER} ); # validation
  9. $bool = $obj->mk_aliases( # create an alias to an existing
  10. alias_name => 'method'); # method name
  11. $clone = $obj->mk_clone; # create a clone of original
  12. # object without data
  13. $bool = $obj->mk_flush; # clean out all data
  14. @list = $obj->ls_accessors; # retrieves a list of all
  15. # accessors for this object
  16. $bar = $obj->foo('bar'); # set 'foo' to 'bar'
  17. $bar = $obj->foo(); # retrieve 'bar' again
  18. $sub = $obj->can('foo'); # retrieve coderef for
  19. # 'foo' accessor
  20. $bar = $sub->('bar'); # set 'foo' via coderef
  21. $bar = $sub->(); # retrieve 'bar' by coderef
  22. ### using the object as base class
  23. package My::Class;
  24. use base 'Object::Accessor';
  25. $obj = My::Class->new; # create base object
  26. $bool = $obj->mk_accessors('foo'); # create accessors, etc...
  27. ### make all attempted access to non-existant accessors fatal
  28. ### (defaults to false)
  29. $Object::Accessor::FATAL = 1;
  30. ### enable debugging
  31. $Object::Accessor::DEBUG = 1;
  32. ### advanced usage -- callbacks
  33. { my $obj = Object::Accessor->new('foo');
  34. $obj->register_callback( sub { ... } );
  35. $obj->foo( 1 ); # these calls invoke the callback you registered
  36. $obj->foo() # which allows you to change the get/set
  37. # behaviour and what is returned to the caller.
  38. }
  39. ### advanced usage -- lvalue attributes
  40. { my $obj = Object::Accessor::Lvalue->new('foo');
  41. print $obj->foo = 1; # will print 1
  42. }
  43. ### advanced usage -- scoped attribute values
  44. { my $obj = Object::Accessor->new('foo');
  45. $obj->foo( 1 );
  46. print $obj->foo; # will print 1
  47. ### bind the scope of the value of attribute 'foo'
  48. ### to the scope of '$x' -- when $x goes out of
  49. ### scope, 'foo's previous value will be restored
  50. { $obj->foo( 2 => \my $x );
  51. print $obj->foo, ' ', $x; # will print '2 2'
  52. }
  53. print $obj->foo; # will print 1
  54. }

DESCRIPTION

Object::Accessor provides an interface to create per object accessors (as opposed to per Class accessors, as, for example, Class::Accessor provides).

You can choose to either subclass this module, and thus using its accessors on your own module, or to store an Object::Accessor object inside your own object, and access the accessors from there. See the SYNOPSIS for examples.

METHODS

$object = Object::Accessor->new( [ARGS] );

Creates a new (and empty) Object::Accessor object. This method is inheritable.

Any arguments given to new are passed straight to mk_accessors .

If you want to be able to assign to your accessors as if they were lvalue s, you should create your object in the Object::Acccessor::Lvalue namespace instead. See the section on LVALUE ACCESSORS below.

$bool = $object->mk_accessors( @ACCESSORS | \%ACCESSOR_MAP );

Creates a list of accessors for this object (and NOT for other ones in the same class!). Will not clobber existing data, so if an accessor already exists, requesting to create again is effectively a no-op.

When providing a hashref as argument, rather than a normal list, you can specify a list of key/value pairs of accessors and their respective input validators. The validators can be anything that Params::Check 's allow function accepts. Please see its manpage for details.

For example:

  1. $object->mk_accessors( {
  2. foo => qr/^\d+$/, # digits only
  3. bar => [0,1], # booleans
  4. zot => \&my_sub # a custom verification sub
  5. } );

Returns true on success, false on failure.

Accessors that are called on an object, that do not exist return undef by default, but you can make this a fatal error by setting the global variable $FATAL to true. See the section on GLOBAL VARIABLES for details.

Note that you can bind the values of attributes to a scope. This allows you to temporarily change a value of an attribute, and have it's original value restored up on the end of it's bound variable's scope;

For example, in this snippet of code, the attribute foo will temporarily be set to 2 , until the end of the scope of $x , at which point the original value of 1 will be restored.

  1. my $obj = Object::Accessor->new;
  2. $obj->mk_accessors('foo');
  3. $obj->foo( 1 );
  4. print $obj->foo; # will print 1
  5. ### bind the scope of the value of attribute 'foo'
  6. ### to the scope of '$x' -- when $x goes out of
  7. ### scope, 'foo' previous value will be restored
  8. { $obj->foo( 2 => \my $x );
  9. print $obj->foo, ' ', $x; # will print '2 2'
  10. }
  11. print $obj->foo; # will print 1

Note that all accessors are read/write for everyone. See the TODO section for details.

@list = $self->ls_accessors;

Returns a list of accessors that are supported by the current object. The corresponding coderefs can be retrieved by passing this list one by one to the can method.

$ref = $self->ls_allow(KEY)

Returns the allow handler for the given key, which can be used with Params::Check 's allow() handler. If there was no allow handler specified, an allow handler that always returns true will be returned.

$bool = $self->mk_aliases( alias => method, [alias2 => method2, ...] );

Creates an alias for a given method name. For all intents and purposes, these two accessors are now identical for this object. This is akin to doing the following on the symbol table level:

  1. *alias = *method

This allows you to do the following:

  1. $self->mk_accessors('foo');
  2. $self->mk_aliases( bar => 'foo' );
  3. $self->bar( 42 );
  4. print $self->foo; # will print 42

$clone = $self->mk_clone;

Makes a clone of the current object, which will have the exact same accessors as the current object, but without the data stored in them.

$bool = $self->mk_flush;

Flushes all the data from the current object; all accessors will be set back to their default state of undef.

Returns true on success and false on failure.

$bool = $self->mk_verify;

Checks if all values in the current object are in accordance with their own allow handler. Specifically useful to check if an empty initialised object has been filled with values satisfying their own allow criteria.

$bool = $self->register_callback( sub { ... } );

This method allows you to register a callback, that is invoked every time an accessor is called. This allows you to munge input data, access external data stores, etc.

You are free to return whatever you wish. On a set call, the data is even stored in the object.

Below is an example of the use of a callback.

  1. $object->some_method( "some_value" );
  2. my $callback = sub {
  3. my $self = shift; # the object
  4. my $meth = shift; # "some_method"
  5. my $val = shift; # ["some_value"]
  6. # could be undef -- check 'exists';
  7. # if scalar @$val is empty, it was a 'get'
  8. # your code here
  9. return $new_val; # the value you want to be set/returned
  10. }

To access the values stored in the object, circumventing the callback structure, you should use the ___get and ___set methods documented further down.

$bool = $self->can( METHOD_NAME )

This method overrides UNIVERAL::can in order to provide coderefs to accessors which are loaded on demand. It will behave just like UNIVERSAL::can where it can -- returning a class method if it exists, or a closure pointing to a valid accessor of this particular object.

You can use it as follows:

  1. $sub = $object->can('some_accessor'); # retrieve the coderef
  2. $sub->('foo'); # 'some_accessor' now set
  3. # to 'foo' for $object
  4. $foo = $sub->(); # retrieve the contents
  5. # of 'some_accessor'

See the SYNOPSIS for more examples.

$val = $self->___get( METHOD_NAME );

Method to directly access the value of the given accessor in the object. It circumvents all calls to allow checks, callbakcs, etc.

Use only if you Know What You Are Doing ! General usage for this functionality would be in your own custom callbacks.

$bool = $self->___set( METHOD_NAME => VALUE );

Method to directly set the value of the given accessor in the object. It circumvents all calls to allow checks, callbakcs, etc.

Use only if you Know What You Are Doing ! General usage for this functionality would be in your own custom callbacks.

$bool = $self->___alias( ALIAS => METHOD );

Method to directly alias one accessor to another for this object. It circumvents all sanity checks, etc.

Use only if you Know What You Are Doing !

LVALUE ACCESSORS

Object::Accessor supports lvalue attributes as well. To enable these, you should create your objects in the designated namespace, Object::Accessor::Lvalue . For example:

  1. my $obj = Object::Accessor::Lvalue->new('foo');
  2. $obj->foo += 1;
  3. print $obj->foo;

will actually print 1 and work as expected. Since this is an optional feature, that's not desirable in all cases, we require you to explicitly use the Object::Accessor::Lvalue class.

Doing the same on the standard Object >Accessor> class would generate the following code & errors:

  1. my $obj = Object::Accessor->new('foo');
  2. $obj->foo += 1;
  3. Can't modify non-lvalue subroutine call

Note that lvalue support on AUTOLOAD routines is a perl 5.8.x feature. See perldoc perl58delta for details.

CAVEATS

  • Allow handlers

    Due to the nature of lvalue subs , we never get access to the value you are assigning, so we can not check it againt your allow handler. Allow handlers are therefor unsupported under lvalue conditions.

    See perldoc perlsub for details.

  • Callbacks

    Due to the nature of lvalue subs , we never get access to the value you are assigning, so we can not check provide this value to your callback. Furthermore, we can not distinguish between a get and a set call. Callbacks are therefor unsupported under lvalue conditions.

    See perldoc perlsub for details.

GLOBAL VARIABLES

$Object::Accessor::FATAL

Set this variable to true to make all attempted access to non-existant accessors be fatal. This defaults to false .

$Object::Accessor::DEBUG

Set this variable to enable debugging output. This defaults to false .

TODO

Create read-only accessors

Currently all accessors are read/write for everyone. Perhaps a future release should make it possible to have read-only accessors as well.

CAVEATS

If you use codereferences for your allow handlers, you will not be able to freeze the data structures using Storable .

Due to a bug in storable (until at least version 2.15), qr// compiled regexes also don't de-serialize properly. Although this bug has been reported, you should be aware of this issue when serializing your objects.

You can track the bug here:

  1. http://rt.cpan.org/Ticket/Display.html?id=1827

BUG REPORTS

Please report bugs or other issues to <bug-object-accessor@rt.cpan.org>.

AUTHOR

This module by Jos Boumans <kane@cpan.org>.

COPYRIGHT

This library is free software; you may redistribute and/or modify it under the same terms as Perl itself.