class::methodmaker(3)
NAME
Class::MethodMaker - a module for creating generic methods
SYNOPSIS
use Class::MethodMaker new_with_init => 'new', get_set => [ qw /foo bar baz / ];
DESCRIPTION
This module solves the problem of having to write a bazil
lion get/set methods that are all the same. The argument
to 'use' is a hash whose keys are the names of types of
generic methods generated by MethodMaker and whose values
tell method maker what methods to make. (More precisely,
the keys are the names of MethodMaker methods (methods
that write methods) and the values are the arguments to
those methods.
To override any generated methods, it is sufficient to
ensure that the overriding method is defined when
Class::MethodMaker is called. Note that the "use" keyword
introduces a "BEGIN" block, so you may need to define (or
at least declare) your overriding method in a "BEGIN"
block.
Some new facilities may be marked as EXPERIMENTAL in the
documentation. These facilities are being trialled, and
whilst it is hoped that they will become mainstream code,
no promises are made. They may change or disappear at any
time. Caveat Emptor. The maintainer would be delighted
to hear any feedback particularly regarding such facili
ties, be it good or bad, so long as it is constructive.
Some old facilities may be marked as COMPATIBILITY in the
documentation. These facilities are being maintained
purely for compatibility with old versions of this module,
but will ultimately disappear. They are normally replaced
by alternatives that are thought preferable for some com
pletely arbitrary raisin. Please avoid using them, and
consider amending any existing code that does use them not
to. If you believe that their removal will cast an unac
ceptable pall over your life, please contact the main
tainer, or get a new life: whichever is easier.
SUPPORTED METHOD TYPES
new
Creates a basic constructor.
Takes a single string or a reference to an array of
strings as its argument. For each string creates a simple
method that creates and returns an object of the appropri
ate class.
This method may be called as a class method, as usual, or
as in instance method, in which case a new object of the
same class as the instance will be created. Note that
"new_hash_init" works slightly differently with regard to
being called on an instance.
new_with_init
Creates a basic constructor which calls a method named
"init" after instantiating the object. The "init" method
should be defined in the class using MethodMaker.
Takes a single string or a reference to an array of
strings as its argument. For each string creates a simple
method that creates an object of the appropriate class,
calls "init" on that object propagating all arguments,
before returning the object.
This method may be called as a class method, as usual, or
as in instance method, in which case a new object of the
same class as the instance will be created. Note that
"new_hash_init" works slightly differently with regard to
being called on an instance.
new_hash_init
Creates a basic constructor which accepts a hash of
slot-name/value pairs with which to initialize the object.
The slot-names are interpreted as the names of methods
that can be called on the object after it is created and
the values are the arguments to be passed to those meth
ods.
Takes a single string or a reference to an array of
strings as its argument. For each string creates a method
that takes a list of arguments that is treated as a set of
key-value pairs, with each such pair causing a call
"$self->key ($value)".
This method may be called as a class method, causing a new
instance to be created, or as an instance method, which
will operate on the subject instance. This allows it to
be combined with new_with_init (see above) to provide some
default values. For example, declare a new_with_init
method, say 'new' and a new_hash_init method, for example,
'hash_init' and then in the init method, you can call mod
ify or add to the %args hash and then call hash_init.
Note that the operation with regard to action on an instance differs to that of "new" and "new_with_init" dif_ ferently with regard to being called on an instance.
new_with_args
Creates a basic constructor.
Takes a single string or a reference to an array of
strings as its argument. For each string creates a simple
method that creates and returns an object of the appropri
ate class.
This method may be called as a class method, as usual, or
as in instance method, in which case a new object of the
same class as the instance will be created. Note that
"new_hash_init" works slightly differently with regard to
being called on an instance.
Constructor arguments will be stored as a key, value pairs
in the object. No check is done regarding the consisten
cies of the data passed to the constructor and the acces
sor methods created.
get_set
Takes a single string or a reference to an array of
strings as its argument. Each string specifies a slot,
for which accessor methods are created. The accessor
methods are, by default:
- x If an argument is provided, sets a new value for x.
- This is true even if the argument is undef (cf. no
argument, which does not set.) - Returns (new) value.
- Value defaults to undef.
- clear_x
- Sets value to undef. This is exactly equivalent to
$foo->x (undef) - No return.
- This is your basic get/set method, and can be used for
slots containing any scalar value, including references to
non-scalar data. Note, however, that MethodMaker has metamethods that define more useful sets of methods for slots
containing references to lists, hashes, and objects. - EXPERIMENTAL: Options
- There are several options available for controlling the
names and types of methods created. - The following options affect the type of methods created:
- -static
- The methods will refer to a class-specific, rather
than instance-specific store. I.e., these scalars are
shared across all instances of your object in your
process. - The following options affect the methods created as
detailed: - -java
- Creates getx and setx methods, which return the value,
and set the value (no return), respectively. - -eiffel
- Creates x and set_x methods, analogous to -java get_x
and set_x respectively. - -compatibility
- Creates x (as per the default), and clear_x, which
resets the slot value to undef. Use this to ensure
backward compatibility. - -noclear
- Creates x (as per the default) only.
- Alternatively, an arrayref specifying a template for
method names may be supplied. Each name must contain a
'*' character, which will be replaced by the slot name,
and no two patterns may be the same. undef may be sup
plied for methods that you do not want created.
Currently, the first 4 members of such an arrayref may be
used: - · Creates a method that if supplied an argument, sets
- the slot to the value of that argument; the value of
the slot (after setting, if relevant) is returned. - 1 Creates a method that takes no arguments, sets the
- slot value to undefined, and makes no return.
- 2 Creates a method that takes no arguments, and returns
- the value of the slot.
- 3 Creates a method that takes one argument, and sets the
- value of the slot to that value. Given undef as that
argument, the value is set to undef. If called with
no arguments, the slot value is set to undef. - See the examples.
- Examples
- Creates methods a, b, c which can be used for both getting
and setting the named slots:
use Class::MethodMakerget_set => 'a',
get_set => [qw/ b c /];- Creates get_d which returns the value in slot d (takes no
arguments), and set_d, which sets the value in slot d (no
return):
use Class::MethodMakerget_set => [ -java => d ];Creates e_clear, e_get, e_set, f_clear, f_get, f_set meth
ods:
use Class::MethodMakerget_set => [[undef, '*_clear', '*_get', '*_set'] =>qw/e f/ ];static_get_setLike get_set, takes a single string or a reference to an
array of strings as its argument. For each string, x cre
ates two methods:x If an argument is provided, sets a new value for x.Returns (new) value. Value defaults to undef.clear_xSets value to undef. No return.The difference between this and get_set is that these
scalars are shared across all instances of your object in
your process.This is now a wrapper around get_set (-static => @args).get_concatLike get_set except sets do not clear out the original
value, but instead concatenate the new value to the exist
ing one. Thus these slots are only good for plain scalars.
Also, like get_set, defines clear_foo method.The argument taken may be a hashref, in which the keys
"name" and "join" are recognized; "name" being the slot
name, join being a join string t glue any given strings.Example:
use Class::MethodMakerget_concat => { name => 'words', join => "" };Will, each time an argument is supplied to the "x" method,
glue this argument onto any existing value with tab sepa
rator. Like the "join" operator, the join field is
applied between values, not prior to the first or after
the last.grouped_fieldsCreates get/set methods like get_set but also defines a
method which returns a list of the slots in the group.
grouped_fields methodssome_group => [ qw / field1 field2 field3 / ];Its argument list is parsed as a hash of group-name =>
field-list pairs. Get-set methods are defined for all the
fields and a method with the name of the group is defined
which returns the list of fields in the group.objectCreates methods for accessing a slot that contains an
object of a given class as well as methods to automati
cally pass method calls onto the object stored in that
slot.
object => ['Foo' => 'phooey',
'Bar' => [ qw / bar1 bar2 bar3 / ],
'Baz' => {slot => 'foo',
comp_mthds => [ qw / bar baz / ]},'Fob' => [{slot => 'dog',
comp_mthds => 'bark',},
{slot => 'cat',
comp_mthds => 'miaow',},];]; - The main argument should be a reference to an array. The
array should contain pairs of class => sub-argument pairs.
The sub-arguments parsed thus: - Hash Reference
- See "Baz" above. The hash should contain the follow
ing keys: - slot
The name of the instance attribute (slot).
- comp_mthds
A string or array ref, naming the methods that
will be forwarded directly to the object in the
slot. - Array Reference
- As for "String", for each member of the array. Also
works if each member is a hash reference (see "Fob"
above). - String
- The name of the instance attribute (slot).
- For each slot "x", with forwarding methods "y" and "z",
the following methods are created: - x A get/set method.
If supplied with an object of an appropriate type,
will set set the slot to that value.- Else, if the slot has no value, then an object is cre
ated by calling new on the appropriate class, passing
in any supplied arguments. - The stored object is then returned.
- y Forwarded onto the object in slot "x", which is auto
- created via "new" if necessary. The "new", if called,
is called without arguments. - z As for "y".
- So, using the example above, a method, "foo", is created
in the class that calls MethodMaker, which can get and set
the value of those objects in slot foo, which will gener
ally contain an object of class Baz. Two additional meth
ods are created in the class using MethodMaker, named
'bar' and 'baz' which result in a call to the 'bar' and
'baz' methods on the Baz object stored in slot foo. - object_list
- Functions like "list", but maintains an array of refer
enced objects in each slot. Forwarded methods return a
list of the results returned by "map"ing the method over
each object in the array. - Arguments are like "object".
- object_tie_list
- Functions like "tie_list", but maintains an array of ref
erenced objects in each slot.
object_tie_list =>[{slot => xxx, # or [ ... , ... ]
tie_array => [ 'ArrayName', args ,...] ,
class => ['ObjName', constructor_args ]},
...]- When xxx is called with one or several arguments, Each
argument is: - · Stored in the array if the argument is an object of
the class 'ObjName'.
- · Used to create a new object of the class 'ObjName' if
the argument is an array ref. The elements of the
array ref are passed to the constructor *after* the
default constructor arguments. - · Discarded if any other case. A new object is created
using the default constructor arguments and stored in
the array. - object_tie_hash
- Functions like "tie_hash", but maintains an array of ref
erenced objects in each slot.
object_tie_hash =>[{slot => xxx, # or [ ... , ... ]
tie_hash => [ 'HashName', args ,...] ,
class => ['ObjName', @constructor_args ]},
...]When xxx is called with more than one argument, xxx is
treated as the key. If the second argument is a:· An object of the class 'ObjName' then the object isthe new value of the key 'xxx'.· An array ref. A new object of the class 'ObjName' iscreated and stored in the hash. The elements of the
array ref are passed to the constructor *after* the
default constructor arguments.· Anything else: A new object is created using thedefault constructor arguments.Example, if the default constructor arguments are @c_args
:
xxx(# xxx[0] = $obj->isa('ObjName') ? $obj : ObjName->new(@c_args)
$obj,
# xxx[1] = ObjName->new(@c_args, arg => 'bar')
[ arg => 'bar'],
# xxx[2 to 8] = ObjName->new(@constructor_arg)1 .. 6)forward
forward => [ comp => 'method1', comp2 => 'method2' ]Define pass-through methods for certain fields. The above
defines that method "method1" will be handled by component
"comp", whilst method "method2" will be handled by compo
nent "comp2".boolean
boolean => [ qw / foo bar baz / ]Creates methods for setting, checking and clearing flags.
All flags created with this meta-method are stored in a
single vector for space efficiency. The argument to
boolean should be a string or a reference to an array of
strings. For each string x it defines several methods:x Returns the value of the x-flag. If called with anargument, it first sets the x-flag to the truth-value
of the argument.set_xEquivalent to x(1).clear_xEquivalent to x(0).Additionally, boolean defines three class methods:bitsReturns the vector containing all of the bit fields
(remember however that a vector containing all 0 bits
is still true).boolean_fieldsReturns a list of all the flags by name.bit_dumpReturns a hash of the flag-name/flag-value pairs.listed_attrib
listed_attrib => [ qw / foo bar baz / ]Like boolean, listed_attrib creates x, set_x, and clear_x methods. However, it also defines a class method x_objects
which returns a list of the objects which presently have
the x-flag set to true. N.B. listed_attrib does not use
the same space efficient implementation as boolean, so
boolean should be prefered unless the x_objects method is
actually needed.key_attrib
key_attrib => [ qw / foo bar baz / ]Creates get/set methods like get/set but also maintains a
hash in which each object is stored under the value of the
field when the slot is set. If an object has a slot set to
a value which another object is already set to the object
currently set to that value has that slot set to undef and
the new object will be put into the hash under that value.
(I.e. only one object can have a given key. The method
find_x is defined which if called with any arguments
returns a list of the objects stored under those values in
the hash. Called with no arguments, it returns a reference
to the hash.key_with_create
key_with_create => [ qw / foo bar baz / ]Just like key_attrib except the find_x method is defined
to call the new method to create an object if there is no
object already stored under any of the keys you give as
arguments.listCreates several methods for dealing with slots containing
list data. Takes a string or a reference to an array of
strings as its argument and for each string, x, creates
the methods:x This method returns the list of values stored in theslot. In an array context it returns them as an array
and in a scalar context as a reference to the array.x_push
x_pop
x_shift
x_unshift
x_splice
x_clear
x_countReturns the number of elements in x.x_indexTakes a list of indices, returns a list of the corre
sponding values.x_setTakes a list, treated as pairs of index => value; each
given index is set to the corresponding value. No
return.tie_listMuch like list, but can use a tied list instead.Takes a list of pairs, where the first is the name of the
component, the second is an array reference. The array
reference takes the usual tie parameters.For instance if Array_A and ArrayB are tied arrays, you
can have:
tie_list =>
[foo => [ 'Array_A', foo => 'x', bar => 'B' ],
baz => [ 'ArrayB', baz => 0]],hashCreates a group of methods for dealing with hash data
stored in a slot.Takes a string or a reference to an array of strings and
for each string, x, creates:x Called with no arguments returns the hash stored inthe slot, as a hash in a list context or as a refer
ence in a scalar context.Called with one simple scalar argument it treats the
argument as a key and returns the value stored under
that key.Called with one array (list) reference argument, the
array elements are considered to be be keys of the
hash. x returns the list of values stored under those
keys (also known as a hash slice.)Called with one hash reference argument, the keys and
values of the hash are added to the hash.Called with more than one argument, treats them as a
series of key/value pairs and adds them to the hash.x_keysReturns the keys of the hash.x_valuesReturns the list of values.x_tallyTakes a list of arguments and for each scalar in the
list increments the value stored in the hash and
returns a list of the current (after the increment)
values.x_existsTakes a single key, returns whether that key exists in
the hash.x_deleteTakes a list, deletes each key from the hash.x_clearResets hash to empty.hash_of_listsCreates a group of methods for dealing with list data
stored by key in a slot.Takes a string or a reference to an array of strings and
for each string, x, creates:x Returns all the values for all the given keys, inorder. If no keys are given, returns all the values
(in an unspecified key order).The result is returned as an arrayref in scalar con
text. This arrayref is not part of the data struc
ture; messing with it will not affect the contents
directly (even if a single key was provided as argu
ment.)If any argument is provided which is an arrayref, then
the members of that array are used as keys. Thus, the
trivial empty-key case may be utilized with an argu
ment of [].x_keysReturns the keys of the hash. As an arrayref in
scalar context.x_existsTakes a list of keys, and returns whether each key
exists in the hash (i.e., the "and" of whether the
individual keys exist).x_deleteTakes a list, deletes each key from the hash.x_pushTakes a key, and some values. Pushes the values onto
the list denoted by the key. If the first argument is
an arrayref, then each element of that arrayref is
treated as a key and the elements pushed onto each
appropriate list.x_popTakes a list of keys, and pops each one. Returns the
list of popped elements. undef is returned in the
list for each key that is has an empty list.x_lastLike "x_pop", but does not actually change any of the
lists.x_unshiftLike push, only the from the other end of the lists.x_shiftLike pop, only the from the other end of the lists.x_spliceTakes a key, offset, length, and a values list.
Splices the list named by the key. Anything from the
offset argument (inclusive) may be omitted. See
"splice" in perlfunc.x_setTakes a key, and a set of index->value pairs, and sets
each specified index to the corresponding value for
the given key.x_clearTakes a list of keys. Resets each named list to empty
(but does not delete the keys.)x_countTakes a list of keys. Returns the sum of the number
of elements for each named list.x_indexTakes a key, and a list of indices. Returns a list of
each item at the corresponding index in the list of
the given key. Uses undef for indices beyond range.x_removeTakes a key, and a list of indices. Removes each cor
responding item from the named list. The indices are
effectively looked up at the point of call --- thus
removing indices 3, 1 from list (a, b, c, d) will
remove (d) and (b).x_siftTakes a key, and a set of named arguments, which may
be a list or a hash ref. Removes list members based
on a grep-like approach.filterThe filter function used (as a coderef). Is
passed two arguments, the value compared against,
and the value in the list that is potential for
grepping out. If returns true, the value is
removed. Default:
sub { $_[0] == $_[1] }keysThe list keys to sift through (as an arrayref).
Unknown keys are ignored. Default: all the known
keys.valuesThe values to sift out (as an arrayref). Default:
"[undef]" - Options:
- -static
- Make the corresponding storage class-specific, rather
than instance-specific. - tie_scalar
- Create a get/set method to deal with the tied scalar.
- Takes a list of pairs, where the first is the name of the
component, the second is an array reference. The array
reference takes the usual tie parameters. - For instance if Enum and Boolean are tied scalar that
accept default values, you can have:
tie_scalar =>
[foo => [ 'Enum', enum => [qw/A B C/], default => 'B'],
bar => [ 'Enum', enum => [qw/T0 T1/], default =>'T1'],
baz => ['Boolean', default => 0]- ],
- tie_hash
- Much like "hash", but uses a tied hash instead.
- Takes a list of pairs, where the first is the name of the
component, the second is a hash reference. The hash ref
erence recognizes the following keys: - tie Required. The name of the class to tie to. Make sure
- you have "use"d the required class.
- args
- Required. Additional arguments for the tie, as an array ref.
- The first argument can also be an arrayref, specifying
multiple components to create. - Example:
tie_hash => [hits => {tie => qw/Tie::RefHash /,
args => [],},- ],
- static_hash
- Much like "hash", but uses a class-based hash instead.
- code
code => [ qw / foo bar baz / ]- Creates a slot that holds a code reference. Takes a string
or a reference to a list of string and for each string, x,
creates a method x which if called with one argument which
is a CODE reference, it installs that code in the slot.
Otherwise it runs the code stored in the slot with what
ever arguments (including none) were passed in. - method
method => [ qw / foo bar baz / ]- Just like code, except the code is called like a method,
with $self as its first argument. Basically, you are cre
ating a method which can be different for each object.
Which is sort of weird. But perhaps useful. - abstract
abstract => [ qw / foo bar baz / ]- This creates a number of methods will die if called. This
is intended to support the use of abstract methods, that
must be overidden in a useful subclass. - counter
- Create components containing simple counters that may be
read, incremented, or reset. For value x, the methods
are: - x (accepts argument to set),
- x_incr
- (accepts argument for increment size),
- x_reset
- The counter is implicitly initialized to zero.
- EXPERIMENTAL: copy
- Produce a copy of self. The copy is a *shallow* copy; any
references will be shared by the instance upon which the
method is called and the returned newborn.
ADDDING NEW METHOD TYPES
MethodMaker is a class that can be inherited. A subclass
can define new method types by writing a method that gen
erates a hash of method_name/code-reference pairs, and
then calls the class method "install_methods" on them. If
the coderef is in fact a string, then that string will be
"eval"led in the hope of getting a coderef to use.
- For example a simple sub-class that defines a method type
upper_case_get_set might look like this: - package Class::MethodMakerSubclass;
- use strict;
- use base qw( Class::MethodMaker );
- sub upper_case_get_set {
my $class = shift;
my ($name) = @_;
my %methods;
$methods{$name} =sub {my ($self, $new) = @_;
defined $new and $self->{$name} = uc $new;
$self->{$name};};$class->install_methods (%methods); - }
- 1;
- Alternatively, rather than a coderef, the values of the
hash passed to install_methods may be strings, which will
be evaled in the hope of returning a coderef to use. If
the eval fails, or anything other than a coderef is
returned, then C::MM croaks. - Any return value from a method (above) that is used to
generate methods will be passed to install_methods --- so
in the above, the line
$class->install_methods (%methods);- could be replaced with
return %methods- EXPERIMENTAL: builtin_class
- History: This method was in 0.92, undocumented. Does any
body use this? Would anybody use this subject to some
enhancement or other? Let me know. - Purpose: This class generates a wrapper around some
builtin function, cacheing the results in the object and
providing a by-name interface. - Takes a (core) function name, and a arrayref of return
position names (we will call it pos_list). Creates: - new Calls the core func with any given arguments, stores
- the result in the instance.
- x For each member of pos_list, creates a method of the
- same name which gets/sets the nth member of the
returned list, where n is the position of x in
pos_list. - fields
- Returns pos_list, in the given order.
- dump
- Returns a list item name, item value, in order.
- Example Usage:
package Stat;- use Class::MethodMaker
builtin_class => [stat => [qw/ dev ino mode nlink /]],
- package main;
- my $file = "$ENV{HOME}/.profile";
my $s = Stat->new ($file);
print "File $file has ", $s->nlink, " links0; - Note that (a) the new method does not check the return
value of the function called (in the above example, if
$file does not exist, you will silently get an empty
object), and (b) if you really want the above example, see
the core File::stat module. But you get the idea, I
hope.
EXAMPLES
BUGS
REPORTING BUGS
Email the author.
AUTHOR
Current Maintainer: Martyn J. Pearce fluffy@cpan.org
Original Author: Peter Seibel (Organic Online)
- Contributions from:
- Dominique Dumont (Dominique_Dumont@hp.com)
Hewlett-Packard Company. http://www.hp.com
- Evolution Online Systems, Inc. http://www.evolution.com
Matthew Persico
Yitzchak Scott-Thoennes
COPYRIGHT
- Copyright (c) 2002, 2001, 2000 Martyn J. Pearce. This
- program is free
software; you can redistribute it and/or modify it un - der the same terms as
Perl itself. - Copyright 1998, 1999, 2000 Evolution Online Systems,
- Inc. You may use
this software for free under the terms of the MIT Li - cense. More info
posted at http://www.evolution.com, or contact in - fo@evolution.com
- Copyright (c) 1996 Organic Online. All rights re
- served. This program is
free software; you can redistribute it and/or modify - it under the same
terms as Perl itself.
SEE ALSO
- C<Class::Struct>, C<Class::MakeMethods>, "Object-Orient
- ed Perl" by Damian
Conway.