Class::MakeMethods::Template - Extensible code templates


NAME

Class::MakeMethods::Template - Extensible code templates


SYNOPSIS

  package MyObject;
  use Class::MakeMethods::Template::Hash (
    'new'       => 'new',
    'string'    => 'foo',
    'number'    => 'bar',
  );


MOTIVATION

If you compare the source code of some of the closure-generating methods provided by other subclasses of Class::MakeMethods, such as the hash accessors provided by the various Standard::* subclasses, you will notice a fair amount of duplication. This module provides a way of assembling common pieces of code to facilitate support the maintenance of much larger libraries of generated methods.


DESCRIPTION

This module extends the Class::MakeMethods framework by providing an abstract superclass for extensible code-templating method generators.

Common types of methods are generalized into template definitions. For example, Template::Generic's new provides a template for methods that create object instances, while Template::Generic's scalar is a template for methods that allow you to get and set individual scalar values.

Thse definitions are then re-used and modified by various template subclasses. For example, the Template::Hash subclass supports blessed-hash objects, while the Template::Static subclass supports shared data; each of them includes an appropriate version of the scalar accessor template for those object types.

Each template defines one or more behaviors, individual methods which can be installed in a calling package, and interfaces, which select from those behaviours and indicate the names to install the methods under.

Each individual meta-method defined by a calling package requires a method name, and may optionally include other key-value parameters, which can control the operation of some meta-methods.


USAGE

Class::MakeMethods Calling Conventions

When you use this package, the method declarations you provide as arguments cause subroutines to be generated and installed in your module.

You can also omit the arguments to use and instead make methods at runtime by passing the declarations to a subsequent call to make().

You may include any number of declarations in each call to use or make(). If methods with the same name already exist, earlier calls to use or make() win over later ones, but within each call, later declarations superceed earlier ones.

You can install methods in a different package by passing -TargetClass => package as your first arguments to use or make.

See the Class::MakeMethods manpage for more details.

Passing Parameters

The following types of Basic declarations are supported:

See the Class::MakeMethods::Catalog manpage for a list of the supported values of generator_type.

For each method name you provide, a subroutine of the indicated type will be generated and installed under that name in your module.

Method names should start with a letter, followed by zero or more letters, numbers, or underscores.

Standard Declaration Syntax

The Standard syntax provides several ways to optionally associate a hash of additional parameters with a given method name.

Basic declarations, as described above, are treated as having an empty parameter hash.

Default Parameters

A set of default parameters to be used for several declarations may be specified using any of the following types of arguments to a Template method generator call:

Parameters set in these ways are passed to each declaration that follows it until the end of the method-generator argument array, or until overridden by another declaration. Parameters specified in a hash for a specific method name, as discussed above, will override the defaults of the same name for that particular method.


PARAMETER REFERENCE

Each meta-method is allocated a hash in which to store its parameters and optional information.

(Note that you can not override parameters on a per-object level.)

Special Parameters

The following parameters are pre-defined or have a special meaning:

Informative Parameters

The following parameters are set automatically when your meta-method is declared:

Other Parameters

Specific subclasses and template types provide support for additional parameters.

Note that you generally should not arbitrarily assign additional parameters to a meta-method unless you know that they do not conflict with any parameters already defined or used by that meta-method.

Parameter Expansion

If a parameter specification contains '*', it is replaced with the primary method name.

Example: The following defines counter (*, *_incr, *_reset) meta-methods j and k, which use the hash keys j_index and k_index to fetch and store their values.

  use Class::MakeMethods::Template::Hash
    counter => [ '-hash_key' => '*_index', qw/ j k / ];

(See the Class::MakeMethods::Template::Hash manpage for information about the hash_key parameter.)

If a parameter specification contains '*{param}', it is replaced with the value of that parameter.

Example: The following defines a Hash scalar meta-method which will store its value in a hash key composed of the defining package's name and individual method name, such as $self->{MyObject-foo}:

  use Class::MakeMethods::Template::Hash
    'scalar' => [ '-hash_key' => '*{target_class}-*{name}', qw/ l / ];

Selecting Interfaces

Each template provides one or more predefined interfaces, each of which specifies one or more methods to be installed in your package, and the method names to use. Check the documentation for specific templates for a list of which interfaces they define.

An interface may be specified for a single method by providing an 'interface' parameter:

Some interfaces provide very different behaviors than the default interface.

Example: The following defines a method g, which if called with an argument appends to, rather than overwriting, the current value:

  use Class::MakeMethods::Template::Hash
    'string' => [ '--get_concat', 'g' ];

A named interface may also be specified as a default in the argument list with a leading '--' followed by the interface's name.

Example: Instead of the normal Hash scalar methods (named x and clear_x), the following creates methods with ``Java-style'' names and behaviors (getx, setx).

  use Class::MakeMethods::Template::Hash
    'scalar' => [ '--java', 'x'  ];

An interface set in this way affects all meta-methods that follow it until another interface is selected or the end of the array is reached; to return to the original names request the 'default' interface.

Example: The below creates ``Java-style'' methods for e and f, ``normal scalar'' methods for g, and ``Eiffel-style'' methods for h.

  use Class::MakeMethods::Template::Hash
    'scalar' => [
      '--java'=> 'e', 'f',
      '--default'=> 'g',
      '--eiffel'=> 'h',
    ];

Selecting Modifiers

You may select modifiers, which will affect all behaviors.

  use Class::MakeMethods::Template::Hash
      'scalar' => [ 'a', '--protected' => 'b', --private' => 'c' ];

Method b croaks if it's called from outside of the current package or its subclasses.

Method c croaks if it's called from outside of the current package.

See the documentation for each template to learn which modifiers it supports.

Runtime Parameter Access

If the meta-method is defined using an interface which includes the attributes method, run-time access to meta-method parameters is available.

Example: The following defines a counter meta-method named y, and then later changes the 'join' parameter for that method at runtime.

  use Class::MakeMethods ( get_concat => 'y' );
  y_attributes(undef, 'join', "\t" )
  print y_attributes(undef, 'join')


EXAMPLES

String and Numeric Accessors

In addition to the scalar accessor supported by the Standard::* classes, the Template subclasses also provide specialized accessors that can facilitate the use of specific types of data.

For example, we could declare the following class to hold information about available Perl packages:

  package MyVersionInfo;
  use Class::MakeMethods::Template::Hash (
    'new'     => 'new',
    'string'  => 'package',
    'number'  => 'version',
  );
  sub summary {
    my $self = shift;
    return $self->package() . " is at version " . $self->version()
  }

You could use this class as follows:

  package main;
  use MyVersionInfo;
  my $obj = MyVersionInfo->new( package=>"Class::MakeMethods");
  $obj->version( 2.0 );
  print $obj->summary();

These accessors will provide a bit of diagnostic type checking; an attempt to call $obj->version("foo") will cause your program to croak.

String Concatenation Interface

The following defines a get_concat method i, and specifies a string to use when joining additional values when this method is called.

  use Class::MakeMethods::Template::Hash
    'string' => [ '--get_concat', 'i', { join => ' - ' } ];

(See the Class::MakeMethods::Template::Generic manpage for information about the string get_concat interface.)

Lazy-Init Interface

Templapte scalar accessors declared with the ``init_and_get'' interface can be used for ``memoization'' or lazy-evaluation for object attributes. If the current accessor value is undefined, they will first call a user-provided init_* method and save its value.

  package MyWidget;
  use Class::MakeMethods::Template::Hash (
    'new --with_values' => [ 'new' ],
    'scalar --init_and_get' => [ 'foo', 'count', 'result' ],
  );
  sub init_foo {
    return 'foofle';
  }
  sub init_count {
    return '3';
  }
  sub init_result {
    my $self = shift;
    return $self->foo x $self->count;
  }
  ...
  my $widget = MyWidget->new();
  print $widget->result; # output: fooflefooflefoofle
  # if values are predefined, the init methods are not used
  my $other_widget = MyWidget->new( foo => 'bar', count => 2 );
  print $widget->result; # output: barbar

(See the Class::MakeMethods::Template::Generic manpage for more information about init_and_get. This interface is also supported by all of Generic's subclasses, so you can add lazy-init methods for global data, class data, array objects, etc. Unfortunately, to date it is only supported for scalar-value accessors...)

Helper Methods

Template methods often include similarly-named ``helper'' methods. For example, specifying the ``--with_clear'' interface for Template::*:scalar methods creates an extra method for each accessor x named clear_x.

  package MyClass;
  use Class::MakeMethods::Template::Hash( 'scalar --with_clear' => 'foo' );
  my $obj = MyClass->new;
  $obj->foo(23);
  $obj->clear_foo;
  print $obj->foo();

Reference Accessor and Helper Methods

For references to arrays and hashes, the Template subclasses provide accessors with extra ``helper methods'' to facilitate method-based interaction.

Here's a class whose instances each store a string and an array reference, along with a method to search the directories:

  package MySearchPath;
  use Class::MakeMethods::Template::Hash (
    'new'     => 'new',
    'string'  => 'name',
    'array'   => 'directories',
  );
  sub search {
    my $self = shift;
    my $target = shift;
    foreach my $dir ( $self->directories ) {
      my $candidate = $dir . '/' . $target;
      return $candidate if ( -e $candidate );
    }
    return;
  }

Note that the directories accessor returns the contents of the array when called in a list context, making it easier to loop over.

And here's a sample usage:

  package main;
  use MySearchPath;
  my $obj = MySearchPath->new( name=>"libs", directories=>['/usr/lib'] );
  $obj->push_directories( '/usr/local/lib' );
  print "Searching in " . $obj->count_directories() . "directories.\n";
  foreach ( 'libtiff', 'libjpeg' ) {
    print "Checking $_: " . ( $obj->search("$_.so") || 'not found' ) . "\n";
  }

Note the use of the push_* and count_* ``helper'' accessor methods, which are defined by default for all 'array' declarations.

Consult the Class::MakeMethods::Template::Generic manpage for more information about the available types of reference accessors, and the various methods they define.

Object Accessors

There's also a specialized accessor for object references:

  package MyStruct;
  use Class::MakeMethods::Template::Hash (
    'new'    => 'new',
    'object' => [ 'widget' => {class=>'MyWidgetClass', delegate=>"twiddle"} ],
  );

(Note that the class and delegate values specified above are method parameters, which provide additional information about the widget declaration; see Standard Declaration Syntax for more information.)

The above declaration creates methods equivalent to the following:

  package MyStruct;
  sub widget {
    my $self = shift;
    if ( scalar @_ ) {
      if (ref $_[0] and UNIVERSAL::isa($_[0], 'MyWidgetClass')) {
        $self->{widget} = shift;
      } else {
        $self->{widget} = MyWidgetClass->new(@_);
      }
    } else {
      return $self->{widget};
    }
  }
  sub clear_widget {
    my $self = shift;
    $self->{widget} = undef;
  }
  sub twiddle {
    my $self = shift;
    my $obj = $self->widget()
      or Carp::croak("Can't forward twiddle because widget is empty");
    $obj->twiddle(@_)
  }

Adding Custom Initialization to Constructors

Frequently you'll want to provide some custom code to initialize new objects of your class. Most of the *:new constructor methods provides a way to ensure that this code is consistently called every time a new instance is created.

Template::Hash:new --and_then_init
Use 'Template::Hash:new --and_then_init', which will first create the object and initialize it with the provided values, and then call an init() method on the new object before returning it.
  package MyClass;
  use Class::MakeMethods::Template::Hash (
    'new --and_then_init' => 'new'
    'string'  => 'foo'
  );
  sub init {
    my $self = shift;
    length($self->foo) or $self->foo('FooBar');   # default value
    warn "Initialized new object '$self'";
  }
  ...
  package main;
  my $self = MyClass->new( foo => 'Foozle' )

Template::Hash:new --with_init
If you don't want your constructor to use the default hash-of-method-names style of initialization, use 'Template::Hash:new --with_init', which will create an empty object, pass its arguments to the init() method on the new object, and then return it.
  package MyClass;
  use Class::MakeMethods::Template::Hash (
    'new --with_init' => 'new'
    'string'  => 'foo'
  );
  sub init {
    my $self = shift;
    $self->foo( shift || 'FooBar' ); # init with arg or default
    warn "Initialized new object '$self'";
  }
  ...
  package main;
  my $self = MyClass->new( 'Foozle' )

Some additional notes about these constructors:

Access Control Example

The following defines a secret_password method, which will croak if it is called from outside of the declaring package.

  use Class::MakeMethods::Template::Hash
    'scalar' => [ '--private', 'secret_password' ];

(See the Class::MakeMethods::Template::Universal manpage for information about the private modifier.)

Changing Method Names

The Template subclasses allow you to control the names assigned to the methods you generate by selecting from several naming interfaces.

For example, the accessors declared above use a default, Perl-ish style interface, in which a single method can be called without an argument to retrieve the value, or with an argument to set it. However, you can also select a more Java-like syntax, with separate get* and set* methods, by including the '--java' template specification:

  package MyStruct;
  use Class::MakeMethods::Template::Hash (
    'new'     => 'new',
    'scalar'  => '--java Foo',
  );

(Note that the declaration of Foo could also have been written as 'scalar --java' => 'Foo' or 'scalar' => ['--java', 'Foo'], or 'scalar' => [ 'foo' = { 'interface'=>'java' } ], all of which are interpreted identically; see the the Class::MakeMethods manpage section on ``Argument Normalization'' for details.)

Usage of this accessor would then be as follows:

  package main;
  use MyStruct;
  my $obj = MyStruct->new( setFoo => "Foozle" );
  print $obj->getFoo();
  $obj->setFoo("Bozzle");

Tree Structure Example

In this example we will create a pair of classes with references to other objects.

The first class is a single-value data object implemented as a reference to a scalar.

  package MyTreeData;
  use Class::MakeMethods::Template::Scalar (
    'new'     => 'new',
    'string'  => 'value',
  );

The second class defines a node in a tree, with a constructor, an accessor for a data object from the class above, and accessors for a list of child nodes.

  package MyTreeNode;
  use Class::MakeMethods::Template::Hash (
    'new'     => 'new',
    'object -class MyTreeData'  => 'data',
    'array_of_objects -class MyTreeNode' => 'children',
  );
  sub depth_first_data {
    my $self = shift;
    return $self->data, map { $_->depth_first_data() } $self->children;
  }

Here's a sample of how the above classes could be used in a program.

  package main;
  use MyTreeData;
  use MyTreeNode;
  my $node = MyTreeNode->new(
      data => { value=>'data1' },
      children => [ { value=>'data3' } ]
  );
  $node->push_children( MyTreeNode->new( data => { value=>'data2' } ) );
  foreach my $data ( $node->depth_first_data ) {
    print $data->value();
  }


SUBCLASS CATALOG

This list summarizes the various subclasses of Class::MakeMethods included in this distribution, and the method types each one provides.

See the documentation for each implementation for more details about the features it provides.

Template::Universal (Any)

Meta-methods for any type of object. See the Class::MakeMethods::Template::Universal manpage.

Template::Ref (Any Instance)

Methods for deep copies and comparisons. See the Class::MakeMethods::Template::Ref manpage.

Template::Generic (Abstract)

The remaining subclasses inherit a similar collection of templates from Template::Generic, and provide a different type of scoping or binding for the functionality defined by the Generic template. See the Class::MakeMethods::Template::Generic manpage for details.

Template::Hash (Generic, Instances)

The most commonly used implementation, for objects based on blessed hashes. See the Class::MakeMethods::Template::Hash manpage.

Template::Struct (Generic, Instances)

Methods for manipulating positional values in arrays. See the Class::MakeMethods::Template::Struct manpage.

Template::Scalar (Generic, Instances)

For objects based on blessed scalars. See the Class::MakeMethods::Template::Scalar manpage.

Note that these objects can generally only have one value accessor method, as all such accessors will refer to the same value.

Template::Flyweight (Generic, Instances)

Stores values for objects in an external location hashed by identity. See the Class::MakeMethods::Template::Flyweight manpage.

Note that while the below constructor creates and returns scalar references, accessor methods can be created with this implementation for use with any type of object.

Template::Static (Generic, Global)

Static methods are not instance-dependent; calling them by class name or from any instance will consistently access the same value. See the Class::MakeMethods::Template::Static manpage.

Template::PackageVar (Generic, Global)

PackageVar methods access a variable in the declaring package. Thus, they have the same effect as Static methods, while keeping their value accessible via the symbol table. See the Class::MakeMethods::Template::PackageVar manpage.

Template::Class (Generic, Global)

Class methods are similar to Static methods, except that each subclass and its instances will access a distinct value. See the Class::MakeMethods::Template::Class manpage.

Template::ClassVar (Generic, Global)

ClassVar methods access a variable in the package on which they are called. Thus, they have the same effect as Class methods, while keeping their value accessible via the symbol table, like PackageVar. See the Class::MakeMethods::Template::ClassVar manpage.

Template::ClassInherit (Generic, Global)

ClassInherit methods are an intermediate point between Static and Class methods; subclasses inherit their superclass's value until they set their own value, after which they become distinct. See the Class::MakeMethods::Template::ClassInherit manpage.


EXTENDING

You can create your own method-generator templates by following the below outline.

Mechanisms

Dynamic generation of methods in Perl generally depends on one of two approaches: string evals, which can be as flexible as your string-manipulation functions allow, but are run-time resource intensive; or closures, which are limited by the number of subroutine constructors you write ahead of time but which are faster and smaller than evals.

Class::MakeMethods::Template uses both of these approaches: To generate different types of subroutines, a simple text-substitution mechanism combines bits of Perl to produce the source code for a subroutine, and then evals those to produce code refs. Any differences which can be handled with only data changes are managed at the closure layer; once the subroutines are built, they are repeatedly bound as closures to hashes of parameter data.

Code Generation

A substitution-based ``macro language'' is used to assemble code strings. This happens only once per specific subclass/template/behavior combination used in your program. (If you have disk-caching enabled, the template interpretation is only done once, and then saved; see below.)

There are numerous examples of this within the Generic interface and its subclasses; for examples, look at the following methods: Universal:generic, Generic:scalar, Hash:generic, and Hash:scalar.

See the Class::MakeMethods::Template::TextBuilder manpage for more information.

Template Definitions

Template method generators are declared by creating a subroutine that returns a hash-ref of information about the template. When these subroutines are first called, the template information is filled in with imported and derived values, blessed as a Class::MakeMethods::Template object, and cached.

Each use of your subclass, or call to its make, causes these objects to assemble the requested methods and return them to Class::MakeMethods for installation in the calling package.

Method generators defined this way will have support for parameters, custom interfaces, and the other features discussed above.

(Your module may also use the ``Aliasing'' and ``Rewriting'' functionality described in EXTENDING in the Class::MakeMethods manpage.)

Definition hashes contain several types of named resources in a second level of hash-refs under the following keys:

Minimum Template Definition

You must at least specify one behavior; all other information is optional.

Class::MakeMethods will automatically fill in the template name and class as 'template_name' and 'template_class' entries in the version of your template definition hash that it caches and uses for future execution.

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

  package Class::MakeMethods::UpperCase;
  use Class::MakeMethods '-isasubclass';
  sub uc_scalar {
    return {
      'behavior' => {
        'default' => sub {
          my $m_info = $_[0];
          return sub {
            my $self = shift;
            if ( scalar @_ ) {
              $self->{ $m_info->{'name'} } = uc( shift )
            } else {
              $self->{ $m_info->{'name'} };
            }
          }
        },
      }
    }
  }

And a caller could then use it to generate methods in their package by invoking:

  Class::MakeMethods::UpperCase->make( 'uc_scalar' => [ 'foo' ] );

Default Parameters

Each template may include a set of default parameters for all declarations as params => hash_ref.

Template-default parameters can be overrridden by interface '-params', described below, and and method-specific parameters, described above.

Defining Interfaces

Template definitions may have one or more interfaces, including the default one, named 'default', which is automatically selected if another interface is not requested. (If no default interface is provided, one is constructed, which simply calls for a behavior named default.)

Most commonly, an interface is specified as a hash which maps one or more subroutine names to the behavior to use for each. The interface subroutine names generally contain an asterisk character, '*', which will be replaced by the name of each meta-method.

Example: The below defines methods e_get, e_set, and e_clear.

  use Class::MakeMethods::Template::Hash
    'scalar' => [
      -interface=>{ '*_clear'=>clear, '*_get'=>'get', '*_set'=>'set' }, 'e'
    ];

If the provided name does not contain an asterisk, it will not be modified for individual meta-methods; for examples, see the bit_fields method generated by Generic bits, and the DESTROY method generated by Flyweight meta-methods.

In addition to the name-to-behavior correspondences described above, interfaces may also contain additional entries with keys begining with the '-' character which are interpreted as follows:

Defining Behaviors

Behaviors can be provided as text which is eval'd to form a closure-generating subroutine when it's first used; $self is automatically defined and assigned the value of the first argument.

      'behavior' => {
        'default' => q{
            if ( scalar @_ ) { $self->{ $m_info->{'name'} } = uc shift }
            $self->{ $m_info->{'name'} };
        },
      }

A simple substitution syntax provides for macro interpretation with definition strings. This functionality is currently undocumented; for additional details see the _interpret_text_builder function in Class::MakeMethods, and review the code_expr hashes defined in Class::MakeMethods::Generic.

Importing

You can copy values out of other template definitions by specifying an '-import' key and corresponding hash reference. You can specify an -import for inside any of the template definition sub-hashes. If no -import is specified for a subhash, and there is a top-level -import value, it is used instead.

Inside an -import hash, provide TemplateClass:type names for each source you wish to copy from, and the values to import, which can be a string, a reference to an array of strings, or '*' to import everything available. (The order of copying is not defined.)

Example: The below definition creates a new template which is identical to an existing one.

  package Class::MakeMethods::MyMethods;
  sub scalarama {
    { -import => { 'Template::Hash:scalar' => '*' } }
  }

Values that are already set are not modified, unless they're an array ref, in which case they're added to.

Example:

  package Class::MakeMethods::MyMethods;
  sub foo_method {
    { 'behavior' => {
      '-init' => [ sub {  warn "Defining foo_method $_[0]->{'name'}" } ],
      'default' => q{ warn "Calling foo_method behavior" }.
    } }
  }
  sub bar_method {
    { 'behavior' => {
      -import => { 'MyMethods:foo_method' => '*' },
      '-init' => [ sub {  warn "Defining bar_method $_[0]->{'name'}" } ],
      'default' => q{ warn "Calling bar_method behavior" }.
    } }
  }

In this case, the bar_method ends up with an array of two '-init' subroutines, its own and the imported one, but only its own default behavior.

Modifying Existing Templates

You can over-write information contained in template definitions to alter their subsequent behavior.

Example: The following extends the Hash:scalar template definition by adding a new interface, and then uses it to create scalar accessor methods named access_p and access_q that get and set values for the hash keys 'p' and 'q':

  Class::MakeMethods::Template::Hash->named_method('scalar')->
          {'interface'}{'frozzle'} = { 'access_*'=>'get_set' };
  package My::Object;
  Class::MakeMethods::Template::Hash->make( 'scalar' => [ --frozzle => qw( p q ) ] );
  $object->access_p('Potato');    # $object->{p} = 'Potato'
  print $object->access_q();      # print $object->{q}

Note that this constitutes ``action at a distance'' and will affect subsequent use by other packages; unless you are ``fixing'' the current behavior, you are urged to create your own template definition which imports the base behavior of the existing template and overrides the information in question.

Example: The following safely declares a new version of Hash:scalar with the desired additional interface:

  package My::Methods;
  sub scalar {
    {
      -import => { 'Template::Hash:scalar' => '*' } ,
      interface => { 'frozzle' => { 'access_*'=>'get_set' } },
    }
  }
  package My::Object;
  My::Methods->make( 'scalar' => [ --frozzle => qw( p q ) ] );

Disk Caching

To enable disk caching of generated code, create an empty directory and pass it to the DiskCache package:

  use Class::MakeMethods::Template::DiskCache qw( /my/code/dir );

This has a mixed effect on performance, but has the notable advantage of letting you view the subroutines that are being generated by your templates.

See the Class::MakeMethods::Template::DiskCache manpage for more information.


SEE ALSO

Getting-Started Resources

Ron Savage has posted a pair of annotated examples, linked to below. Each demonstrates building a class with MakeMethods, and each includes scads of comments that walk you through the logic and demonstrate how the various methods work together.

  http://savage.net.au/Perl-tutorials.html
  http://savage.net.au/Perl-tutorials/tut-33.tgz
  http://savage.net.au/Perl-tutorials/tut-34.tgz

Package Documentation

See the Class::MakeMethods manpage for an overview of this framework and the general calling conventions for use and make.

See the Class::MakeMethods::Template manpage for information about this family of subclasses.

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

 Class::MakeMethods::Template - Extensible code templates