The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Class::MakeMethods::Template - Extensible code templates

SYNOPSIS

  package MyObject;
  use Class::MakeMethods::Template::Hash (
    'new'       => 'new',
    'string'    => 'foo',
    'number'    => 'bar',
  );
   
  my $obj = MyObject->new( foo => "Foozle", bar => 23 );
  print $obj->foo();
  $obj->bar(42);

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::Global 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 Class::MakeMethods for more details.

Passing Parameters

The following types of Basic declarations are supported:

  • generator_type => "method_name"

  • generator_type => "name_1 name_2..."

  • generator_type => [ "name_1", "name_2", ...]

See "TEMPLATE CLASSES" in Class::MakeMethods::Docs::Catalog 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.

  • generator_type => [ "name_1" => { param=>value... }, ... ]

    A hash of parameters to use just for this method name.

    (Note: to prevent confusion with self-contained definition hashes, described below, parameter hashes following a method name must not contain the key 'name'.)

  • generator_type => [ [ "name_1", "name_2", ... ] => { param=>value... } ]

    Each of these method names gets a copy of the same set of parameters.

  • generator_type => [ { "name"=>"name_1", param=>value... }, ... ]

    By including the reserved parameter name, you create a self contained declaration with that name and any associated hash values.

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:

  • '-param' => 'value'

    Set a default value for the specified parameter.

  • '--' => { 'param' => 'value', ... }

    Set default values for one or more parameters. Equivalent to a series of '-param' => 'value' pairs for each pair in the referenced hash.

  • '--special_param_value'

    Specifies a value for special parameter; the two supported parameter types are:

    -

    '--interface_name'

    Select a predefined interface; equivalent to '-interface'=> 'interface_name'.

    For more information about interfaces, see "Selecting Interfaces" below.

    -

    '--modifier_name'

    Select a global behavior modifier, such as '--private' or '--protected'.

    For more information about modifiers, see "Selecting Modifiers" below.

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:

  • name

    The primary name of the meta-method. Note that the subroutines installed into the calling package may be given different names, depending on the rules specified by the interface.

  • interface

    The name of a predefined interface, or a reference to a custom interface, to use for this meta-method. See "Selecting Interfaces", below.

  • modifier

    The names of one or more predefined modifier flags. See "Selecting Modifiers", below.

Informative Parameters

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

  • target_class

    The class that requested the meta-method, into which its subroutines will be installed.

  • template_name

    The Class::MakeMethods::Template method used for this declaration.

  • template_class

    The Class::MakeMethods::Template subclass used for this declaration.

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 Class::MakeMethods::Template::Hash 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:

  • 'interface_name'

    Select a predefined interface.

    Example: Instead of the normal Hash scalar method named x, the following creates methods with "Java-style" names and behaviors, getx and setx.

      use Class::MakeMethods::Template::Hash
        'scalar' => [ 'x' => { interface=>'java' } ];

    (See "scalar" in Class::MakeMethods::Template::Generic for a description of the java interface.)

  • 'behavior_name'

    A simple interface consisting only of the named behavior.

    For example, the below declaration creates a read-only methods named q. (There are no set or clear methods, so any value would have to be placed in the hash by other means.)

      use Class::MakeMethods::Template::Hash (
        'scalar' => [ 'q' => { interface=>'get' } ] 
      );
  • { 'subroutine_name_pattern' => 'behavior_name', ... }

    A custom interface consists of a hash-ref that maps subroutine names to the associated behaviors. Any * characters in subroutine_name_pattern are replaced with the declared method name.

    For example, the below delcaration creates paired get_w and set_w methods:

      use Class::MakeMethods::Template::Hash (
        'scalar' => [ 'w' => { interface=> { 'get_*'=>'get', 'set_*'=>'set' } } ] 
      );

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')

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 Class::MakeMethods::Utility::TextBuilder 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 Class::MakeMethods.)

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 InsideOut 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:

  • -params => hash_ref

    Interfaces may include a '-params' key and associated reference to a hash of default parameters for that interface.

  • -base => interface_name

    Interfaces can be based on previously existing ones by including a -base specification in the the hash. The base value should contain one or more space-separated names of the interfaces to be included.

    Example: The below defines methods getG, setG, and clearG.

      use Class::MakeMethods::Template::Hash
        'scalar' => [
          -interface => { -base=>'java', 'clear*'=>'clear' }, qw/ G / 
        ];

    If multiple interfaces are included in the -base specification and specify different behaviors for the same subroutine name, the later ones will override the earlier. Names which appear in the base interface can be overridden by providing a new value, or a name can be removed by mapping it to undef or the empty string.

    Example: The following defines a get-set meta-method h, but supresses the clear_h method:

      use Class::MakeMethods::Template::Hash
        'scalar' => [
          -interface => { -base=>'with_clear', 'clear_*'=>'' }, qw/ h / 
        ];

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::Utility::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 Class::MakeMethods::Utility::DiskCache for more information.

SEE ALSO

See Class::MakeMethods for general information about this distribution.

See Class::MakeMethods::Examples for some illustrations of what you can do with this package.

For distribution, installation, support, copyright and license information, see Class::MakeMethods::Docs::ReadMe.