NAME

Class::MakeMethods - Generate common types of methods

SYNOPSIS

 package MyObject;
 use Class::MakeMethods::Basic::Hash (
   'new'     => [ 'new' ],
   'scalar'  => [ 'foo', 'bar' ]
 );

 package main;   

 my $obj = MyObject->new( foo => "Foozle", bar => "Bozzle" );
 print $obj->foo();
 $obj->bar("Barbados");

MOTIVATION

"Make easy things easier."

This module addresses a problem encountered in object-oriented development wherein numerous methods are defined which differ only slightly from each other.

A common example is accessor methods for hash-based object attributes, which allow you to get and set the value self->{foo} by calling a method self->foo().

These methods are generally quite simple, requiring only a couple of lines of Perl, but in sufficient bulk, they can cut down on the maintainability of large classes.

Class::MakeMethods allows you to simply declare those methods to be of a predefined type, and it generates and installs the necessary methods in your package at compile-time.

DESCRIPTION

The Class::MakeMethods framework allows Perl class developers to quickly define common types of methods. When a module uses a subclass of Class::MakeMethods, it can select from the supported method types, and specify a name for each method desired. The methods are dynamically generated and installed in the calling package.

Extensible Architecture

The Class::MakeMethods package defines a superclass for method-generating modules, and provides a calling convention, on-the-fly subclass loading, and subroutine installation that will be shared by all subclasses.

Construction of the individual methods is handled by subclasses. This delegation approach allows for a wide variety of method-generation techniques to be supported, each by a different subclass. Subclasses can also be added to provide support for new types of methods.

Over a dozen subclasses are included, including implementations of a variety of different method-generation techniques. Each subclass generates several types of methods, with some supporting their own open-eneded extension syntax, for hundreds of possible combinations of method types. (See Class::MakeMethods::Guide for an overview of the included subclasses.)

Getting Started

The remainder of this document focuses on points of usage that are common across all subclasses, and describes how to create your own subclasses.

If this is your first exposure to Class::MakeMethods, you may want to start with Class::MakeMethods::Guide, and then perhaps jump to the documentation for a few of the included subclasses, before returning to the details presented below.

USAGE

The supported method types, and the kinds of arguments they expect, vary from subclass to subclass; see the documentation of each subclass for details.

However, the features described below are applicable to all subclasses.

Invocation

Methods are dynamically generated and installed into the calling package when you use Class::MakeMethods (...) or one of its subclasses, or if you later call Class::MakeMethods->make(...).

The arguments to use or make should be pairs of a generator type name and an associated array of method-name arguments to pass to the generator.

  • use Class::MakeMethods::MethodClass ( 'MethodType' => [ Arguments ], ... );

  • Class::MakeMethods::MethodClass->make ( 'MethodType' => [ Arguments ], ... );

The difference between use and make is primarily one of precedence; the use keyword acts as a BEGIN block, and is thus evaluated before make would be. (See "About Precedence" in Class::MakeMethods::Guide for additional discussion of this issue.)

Note: If you are using Perl version 5.6 or later, see Class::MakeMethods::Attribute for an additional declaration syntax for generated methods.

  • use Class::MakeMethods::Attribute 'MethodClass';

    sub name :MakeMethod('MethodType' => Arguments);

Global Options

Global parameters may be specified as an argument pair with a leading hyphen. (Type names must be valid Perl identifiers, and thus will never begin with a hyphen.)

use Class::MakeMethods::MethodClass ( '-Param' => ParamValue, 'MethodType' => [ Arguments ], ... );

Parameter settings apply to all subsequent method declarations within a single use or make call.

The below parameters allow you to control generation and installation of the requested methods. (Some subclasses may support additional parameters; see their documentation for details.)

TargetClass

By default, the methods are installed in the first package in the caller() stack that is not a Class::MakeMethods subclass; this is generally the package in which your use or make statement was issued. To override this you can pass -TargetClass => package as initial arguments to use or make.

This allows you to construct or modify classes "from the outside":

package main;

use Class::MakeMethods::Basic::Hash( 
  -TargetClass => 'MyWidget',
  'new' => ['create'],
  'scalar' => ['foo', 'bar'],
);

$o = MyWidget->new( foo => 'Foozle' );
print $o->foo();
MakerClass

By default, meta-methods are looked up in the package you called use or make on.

You can override this by passing the -MakerClass flag, which allows you to switch packages for the remainder of the meta-method types and arguments.

use Class::MakeMethods ( '-MakerClass'=>'MethodClass', 'MethodType' => [ Arguments ] );

You may also select a specific subclass of Class::MakeMethods for a single meta-method type/argument pair by prefixing the type name with a subclass name and a colon.

use Class::MakeMethods ( 'MethodClass:MethodType' => [ Arguments ] );

When specifying the MakerClass, you may provide either the trailing part name of a subclass inside of the Class::MakeMethods:: namespace, or a full package name prefixed by ::.

For example, the following four statements are equivalent ways of declaring a Basic::Hash scalar method named 'foo':

use Class::MakeMethods::Basic::Hash ( 
  'scalar' => [ 'foo' ] 
);

use Class::MakeMethods ( 
  '-MakerClass'=>'Basic::Hash', 
  'scalar' =>  [ 'foo' ] 
);

use Class::MakeMethods ( 
  'Basic::Hash:scalar' => [ 'foo' ] 
);

use Class::MakeMethods ( 
  '-MakerClass'=>'::Class::MakeMethods::Basic::Hash', 
  'scalar' =>  [ 'foo' ] 
);
ForceInstall

By default, Class::MakeMethods will not install generated methods over any pre-existing methods in the target class. To override this you can pass -ForceInstall => 1 as initial arguments to use or make.

Note that the use keyword acts as a BEGIN block, so a use at the top of a file will be executed before any subroutine declarations later in the file have been seen. (See "About Precedence" in Class::MakeMethods::Guide for additional discussion of this issue.)

Argument Normalization

The following expansion rules are applied to argument pairs to enable the use of simple strings instead of arrays of arguments.

  • Each type can be followed by a single meta-method definition, or by a reference to an array of them.

  • If the argument is provided as a string containing spaces, it is split and each word is treated as a separate argument.

  • It the meta-method type string contains spaces, it is split and only the first word is used as the type, while the remaining words are placed at the front of the argument list.

For example, the following statements are equivalent ways of declaring a pair of Basic::Hash scalar methods named 'foo' and 'bar':

use Class::MakeMethods::Basic::Hash ( 
  'scalar' => [ 'foo', 'bar'], 
);

use Class::MakeMethods::Basic::Hash ( 
  'scalar' => 'foo', 
  'scalar' => 'bar', 
);

use Class::MakeMethods::Basic::Hash ( 
  'scalar' => 'foo bar', 
);

use Class::MakeMethods::Basic::Hash ( 
  'scalar foo' => 'bar', 
);

(The last of these is clearly a bit peculiar and potentially misleading if used as shown, but it enables advanced subclasses to provide convenient formatting for declarations with defaults or modifiers, such as 'Template::Hash:scalar --private' => 'foo'.)

EXTENDING

Class::MakeMethods can be extended by creating subclasses that define additional meta-method types. Callers then select your subclass using any of the several techniques described above.

You can give your meta-method type any name that is a legal subroutine identifier. Names begining with an underscore, and the names import and make, are reserved for internal use by Class::MakeMethods.

Implementation Options

Your meta-method subroutine should provide one of the following types of functionality:

  • Subroutine Generation

    Returns a list of subroutine name/code pairs.

    The code returned may either be a coderef, or a string containing Perl code that can be evaled and will return a coderef. If the eval fails, or anything other than a coderef is returned, then Class::MakeMethods croaks.

    For example a simple sub-class with a method type upper_case_get_set that generates an accessor method for each argument provided might look like this:

      package Class::UpperCaseMethods;
      use Class::MakeMethods '-isasubclass';
      
      sub uc_scalar {
        my $class = shift;
        map { 
          my $name = $_;
          $name => sub {
    	my $self = shift;
    	if ( scalar @_ ) { 
    	  $self->{ $name } = uc( shift ) 
    	} else {
    	  $self->{ $name };
    	}
          }
        } @_;
      }

    Callers could then generate these methods as follows:

    use Class::UpperCaseMethods ( 'uc_scalar' => 'foo' );
  • Aliasing

    Returns a string containing a different meta-method type to use for those same arguments.

    For example a simple sub-class that defines a method type stored_value might look like this:

    package Class::UpperCaseMethods;
    use Class::MakeMethods '-isasubclass';
    
    sub regular_scalar { return 'Basic::Hash:scalar' }

    And here's an example usage:

    use Class::UpperCaseMethods ( 'regular_scalar' => [ 'foo' ] );
  • Rewriting

    Returns one or more array references with different meta-method types and arguments to use.

    For example, the below meta-method definition reviews the name of each method it's passed and creates different types of meta-methods based on whether the declared name is in all upper case:

      package Class::UpperCaseMethods;
      use Class::MakeMethods '-isasubclass';
    
      sub auto_detect { 
        my $class = shift;
        my @rewrite = ( [ 'Basic::Hash:scalar' ], 
    		    [ '::Class::UpperCaseMethods:uc_scalar' ] );
        foreach ( @_ ) {
          my $name_is_uppercase = ( $_ eq uc($_) ) ? 1 : 0;
          push @{ $rewrite[ $name_is_uppercase ] }, $_
        }
        return @rewrite;
      }

    The following invocation would then generate a regular scalar accessor method foo, and a uc_scalar method BAR:

    use Class::UpperCaseMethods ( 'auto_detect' => [ 'foo', 'BAR' ] );
  • Generator Object

    Returns an object with a method named make_methods which will be responsible for returning subroutine name/code pairs.

    See Class::MakeMethods::Template for an example.

  • Self-Contained

    Your code may do whatever it wishes, and return an empty list.

Access to Parameters

Global parameter values are available through the _context() class method:

  • TargetClass

    Class into which code should be installed.

  • MakerClass

    Which subclass of Class::MakeMethods will generate the methods?

  • ForceInstall

    Controls whether generated methods will be installed over pre-existing methods in the target package.

DIAGNOSTICS

The following warnings and errors may be produced when using Class::MakeMethods to generate methods. (Note that this list does not include run-time messages produced by calling the generated methods.)

These messages are classified as follows (listed in increasing order of desperation):

(Q) A debugging message, only shown if $CONTEXT{Debug} is true
(W) A warning.
(D) A deprecation.
(F) A fatal error in caller's use of the module.
(I) An internal problem with the module or subclasses.

Portions of the message which may vary are denoted with a %s.

Can't interpret meta-method template: argument is empty or undefined

(F)

Can't interpret meta-method template: unknown template name '%s'

(F)

Can't interpret meta-method template: unsupported template type '%s'

(F)

Can't make method %s(): template specifies unknown behavior '%s'

(F)

Can't parse meta-method declaration: argument is empty or undefined

(F) You passed an undefined value or an empty string in the list of meta-method declarations to use or make.

Can't parse meta-method declaration: missing name attribute.

(F) You included an hash-ref-style meta-method declaration that did not include the required name attribute. You may have meant this to be an attributes hash for a previously specified name, but if so we were unable to locate it.

Can't parse meta-method declaration: unknown template name '%s'

(F) You included a template specifier of the form '-template_name' in a the list of meta-method declaration, but that template is not available.

Can't parse meta-method declaration: unsupported declaration type '%s'

(F) You included an unsupported type of value in a list of meta-method declarations.

Compilation error: %s

(I)

Not an interpretable meta-method: '%s'

(I)

Odd number of arguments passed to %s make

(F) You specified an odd number of arguments in a call to use or make. The arguments should be key => value pairs.

Unable to compile generated method %s(): %s

(I) The install_methods subroutine attempted to compile a subroutine by calling eval on a provided string, which failed for the indicated reason, usually some type of Perl syntax error.

Unable to dynamically load $package: $%s

(F)

Unable to install code for %s() method: '%s'

(I) The install_methods subroutine was passed an unsupported value as the code to install for the named method.

Unexpected return value from compilation of %s(): '%s'

(I) The install_methods subroutine attempted to compile a subroutine by calling eval on a provided string, but the eval returned something other than than the code ref we expect.

Unexpected return value from meta-method constructor %s: %s

(I) The requested method-generator was invoked, but it returned an unacceptable value.

SEE ALSO

See Class::MakeMethods::Guide for a getting-started guide, annotated examples of usage, and a listing of the method generation classes included in this distribution.

See Class::MakeMethods::ReadMe for distribution, installation, version and support information.

For a brief survey of the numerous modules on CPAN which offer some type of method generation, see Class::MakeMethods::RelatedModules.

Perl Docs

See "Making References" in perlref, point 4 for more information on closures.

See perltoot and perltootc for an extensive discussion of various approaches to class construction.

VERSION

This is Class::MakeMethods v1.0.13.

AUTHORS

Developed by
M. Simon Cavalletto, Evolution Online Systems, simonm@evolution.com
The Shoulders of Giants

Inspiration, cool tricks, and blocks of useful code for this module were extracted from the following CPAN modules:

Class::MethodMaker, by Peter Seibel.
Class::Accessor, by Michael G Schwern 
Class::Contract, by Damian Conway
Class::SelfMethods, by Toby Everett
Feedback and Suggestions
Martyn J. Pearce
Scott R. Godin
Ron Savage
Jay Lawrence

LICENSE

This module is free software. It may be used, redistributed and/or modified under the same terms as Perl.

Copyright (c) 1998, 1999, 2000, 2001 Evolution Online Systems, Inc.

Portions Copyright (c) 1996 Organic Online

Portions Copyright (c) 2000 Martyn J. Pearce.

2 POD Errors

The following errors were encountered while parsing the POD:

Around line 433:

L<> starts or ends with whitespace

Around line 532:

L<> starts or ends with whitespace