MakeMethods(3pm)

๐Ÿ“ฆ
version 1.01 ยท 5 versions
, in ubuntu noble, ubuntu resolute, ubuntu stonking

okay bestie, welcome to Class::MakeMethods(3pm) โ€” it's a User Contributed Perl Documentation page, and it's literally about making Perl methods show up on demand like a magic trick ๐Ÿ’…โœจ

โœจ NAME โœจ

Class::MakeMethods โ€” Generate common types of methods

๐ŸŒˆ SYNOPSIS ๐ŸŒˆ

  # Generates methods for your object when you "use" it.
  package MyObject;
  use Class::MakeMethods::Standard::Hash (
    'new'       => 'new',
    'scalar'    => 'foo',
    'scalar'    => 'bar',
  );

  # The generated methods can be called just like normal ones
  my $obj = MyObject->new( foo => "Foozle", bar => "Bozzle" );
  print $obj->foo();
  $obj->bar("Barbados");

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

The Class::MakeMethods framework lets Perl class developers quickly define common types of methods, no cap. When a module uses Class::MakeMethods or one of its subclasses, it can pick from a bunch of supported method types and give a name for each method it wants. Then those methods get dynamically generated and installed in the calling package. โœจ

The actual construction of each individual method is handled by subclasses. This delegation approach is iconic because it lets a wide variety of method-generation techniques be supported, each by a different subclass. Subclasses can also be added to provide support for new types of methods. ๐Ÿซถ

There are over a dozen subclasses available, including implementations of a variety of different method-generation techniques. Each subclass generates several types of methods, with some supporting their own open-ended extension syntax, for hundreds of possible combinations of method types. Literally a whole method buffet. ๐Ÿ“

๐ŸŒธ GETTING STARTED ๐ŸŒธ

๐Ÿ’– 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. periodt.

๐ŸŽ€ A Contrived Example ๐ŸŽ€

Object-oriented Perl code is widespread โ€” you've probably seen code like the below a million times:

  my $obj = MyStruct->new( foo=>"Foozle", bar=>"Bozzle" );
  if ( $obj->foo() =~ /foo/i ) {
    $obj->bar("Barbados!");
  }
  print $obj->summary();

(If this doesn't look familiar, take a moment to read perlboot and you'll soon learn more than's good for you.)

Typically, this involves creating numerous subroutines that follow a handful of common patterns, like constructor methods and accessor methods. The classic 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.

Here's a possible implementation for the class whose interface is shown above:

  package MyStruct;

  sub new {
    my $callee = shift;
    my $self = bless { @_ }, (ref $callee || $callee);
    return $self;
  }

  sub foo {
    my $self = shift;
    if ( scalar @_ ) {
      $self->{'foo'} = shift();
    } else {
      $self->{'foo'}
    }
  }

  sub bar {
    my $self = shift;
    if ( scalar @_ ) {
      $self->{'bar'} = shift();
    } else {
      $self->{'bar'}
    }
  }

  sub summary {
    my $self = shift;
    join(', ', map { "\u$_: " . $self->$_() } qw( foo bar ) )
  }

Note in particular that the foo and bar methods are almost identical, and that the new method could be used for almost any class; this is precisely the type of redundancy Class::MakeMethods addresses. ๐ŸŽฏ

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.

Here's the equivalent declaration for that same basic class:

  package MyStruct;
  use Class::MakeMethods::Standard::Hash (
    'new'       => 'new',
    'scalar'    => 'foo',
    'scalar'    => 'bar',
  );

  sub summary {
    my $self = shift;
    join(', ', map { "\u$_: " . $self->$_() } qw( foo bar ) )
  }

This is the basic purpose of Class::MakeMethods: The "boring" pieces of code have been replaced by succinct declarations, placing the focus on the "unique" or "custom" pieces. ๐Ÿ‘‘

๐Ÿงš Finding the Method Types You Need ๐Ÿงš

Once you've grasped the basic idea โ€” simplifying repetitive code by generating and installing methods on demand โ€” the remaining complexity basically boils down to figuring out which arguments to pass to generate the specific methods you want. iykyk.

Unfortunately, this is not a trivial task, as there are dozens of different types of methods that can be generated, each with a variety of options, and several alternative ways to write each method declaration. You may prefer to start by just finding a few examples that you can modify to accomplish your immediate needs, and defer investigating all of the extras until you're ready to take a closer look. ๐Ÿ™ˆ

๐ŸŒŸ Other Documentation ๐ŸŒŸ

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 skim over the rest of this document, then take a look at the examples and one or two of the method-generating subclasses to get a more concrete sense of typical usage, before returning to the details presented below. ๐Ÿ’–

  • A collection of sample uses is available in Class::MakeMethods::Docs::Examples.
  • Some of the most common object and class methods are available from Class::MakeMethods::Standard::Hash, Class::MakeMethods::Standard::Global and Class::MakeMethods::Standard::Universal.
  • If you need a bit more flexibility, see Class::MakeMethods::Composite for method generators which offer more customization options, including pre- and post-method callback hooks. ๐Ÿช
  • For the largest collection of methods and options, see Class::MakeMethods::Template, which uses a system of dynamic code generation to allow endless variation. ๐Ÿ”ฅ
  • A listing of available method types from each of the different subclasses is provided in Class::MakeMethods::Docs::Catalog.

๐Ÿ—๏ธ CLASS ARCHITECTURE ๐Ÿ—๏ธ

Okay so bestie, there are so many common types of methods you might want to generate, and the Class::MakeMethods framework handles that with an extensible system based on subclasses. It's giving modular queen energy ๐Ÿ’….

When your code requests a method, the MakeMethods base class does some standard argument parsing, delegates the actual construction of the method to the appropriate subclass, and then installs whatever method the subclass returns. No cap, that's the whole loop.

๐Ÿงš The MakeMethods Base Class ๐Ÿงš

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. It's the main character that makes the whole friend group work ๐Ÿ’–.

The superclass also lets you generate several different types of methods in a single call, and will automatically load named subclasses the first time they're used. Lowkey iconic.

๐Ÿ› ๏ธ The Method Generator Subclasses ๐Ÿ› ๏ธ

The type of method that gets created is controlled by the specific subclass and generator function you request. For example, Class::MakeMethods::Standard::Hash has a generator function scalar(), which is responsible for generating simple scalar-accessor methods for blessed-hash objects. Slay.

Each generator function specified is passed the arguments specifying the method the caller wants, and produces a closure or eval-able sequence of Perl statements representing the ready-to-install function. Very "build the function, then ship it" of it all โœจ.

๐ŸŽ€ Included Subclasses ๐ŸŽ€

Because each subclass defines its own set of method types and customization options, a key step is to find your way to the appropriate subclasses. Think of it like finding the right group chat for the vibe you need ๐Ÿซถ.

๐ŸŒธ Standard (See Class::MakeMethods::Standard.)

Generally you will want to begin with the Standard::Hash subclass, to create constructor and accessor methods for working with blessed-hash objects (or you might choose the Standard::Array subclass instead). The Standard::Global subclass provides methods for class data shared by all objects in a class.

Each Standard method declaration can optionally include a hash of associated parameters, which allows you to tweak some of the characteristics of the methods. Subroutines are bound as closures to a hash of each method's name and parameters. Standard::Hash and Standard::Array provide object constructor and accessors. The Standard::Global provides for static data shared by all instances and subclasses, while the data for Standard::Inheritable methods trace the inheritance tree to find values, and can be overridden for any subclass or instance. Family tree tea โ˜•.

๐ŸŒˆ Composite (See Class::MakeMethods::Composite.)

For additional customization options, check out the Composite subclasses, which allow you to select from a more varied set of implementations and which allow you to adjust any specific method by adding your own code-refs to be run before or after it. It's literally "method with a little pre-game and post-game" energy ๐Ÿ’….

Subroutines are bound as closures to a hash of each method's name and optional additional data, and to one or more subroutine references which make up the composite behavior of the method. Composite::Hash and Composite::Array provide object constructor and accessors. The Composite::Global provides for static data shared by all instances and subclasses, while the data for Composite::Inheritable methods can be overridden for any subclass or instance.

๐Ÿงต Template (See Class::MakeMethods::Template.)

The Template subclasses provide an open-ended structure for objects that assemble Perl code on the fly into cachable closure-generating subroutines; if the method you need isn't included, you can extend existing methods by re-defining just the snippet of code that's different. That's the "copy the fit, change the shoes" approach ๐Ÿ‘‘.

Class::MakeMethods::Template extends MakeMethods with a text templating system that can assemble Perl code fragments into a desired subroutine. The code for generated methods is eval'd once for each type, and then repeatedly bound as closures to method-specific data for better performance. Efficiency and drama, we love to see it.

Templates for dozens of types of constructor, accessor, and mutator methods are included, ranging from the mundane (constructors and value accessors for hash and array slots) to the esoteric (inheritable class data and "inside-out" accessors with external indexes). From basic to deeply weird, the range is real ๐ŸŒˆ.

๐Ÿ’œ Basic (See Class::MakeMethods::Basic.)

The Basic subclasses provide stripped down method generators with no configurable options, for minimal functionality (and minimum overhead). Sometimes you don't need the whole glam team, just the essentials.

Subroutines are bound as closures to the name of each method. Basic::Hash and Basic::Array provide simple object constructors and accessors. Basic::Global provides basic global-data accessors.

๐Ÿฆ‹ Emulators (See Class::MakeMethods::Emulator.)

In several cases, Class::MakeMethods provides functionality closely equivalent to that of an existing module, and it is simple to map the existing module's interface to that of Class::MakeMethods. It's the "we have that at home, but actually good" situation ๐Ÿซถ.

Emulators are included for Class::MethodMaker, Class::Accessor::Fast, Class::Data::Inheritable, Class::Singleton, and Class::Struct, each of which passes the original module's test suite, usually requiring only that the name of the module be changed. Test suite passing? We love a flawless transition ๐Ÿ’–.

๐ŸŒฑ Extending

Class::MakeMethods can be extended by creating subclasses that define additional method-generation functions. Callers can then specify the name of your subclass and generator function in their use Call::MakeMethods ... statements and your function will be invoked to produce the required closures. See "EXTENDING" for more information. Build your own little method factory, bestie ๐Ÿ› ๏ธ.

๐Ÿ”ฎ Naming Convention for Generated Method Types ๐Ÿ”ฎ

Method generation functions in this document are often referred to using the 'MakerClass:MethodType' or 'MakerGroup::MakerSubclass:MethodType' naming conventions. As you will see, these are simply the names of Perl packages and the names of functions that are contained in those packages. No mysterious lore, just package names ๐Ÿ’€.

The included subclasses are grouped into several major groups, so the names used by the included subclasses and method types reflect three axes of variation, "Group::Subclass:Type":

  • Maker Group โ€” each group shares a similar style of technical implementation and level of complexity. For example, the Standard::* packages are all simple, while the Composite::* packages all support pre- and post-conditions.

(For a listing of the four main groups of included subclasses, see "Included Subclasses"" in ".".)

  • Maker Subclass โ€” each subclass generates methods for a similar level of scoping or underlying object type. For example, the *::Hash packages all make methods for objects based on blessed hashes, while the *::Global packages make methods that access class-wide data that will be shared between all objects in a class.
  • Method Type โ€” each method type produces a similar type of constructor or accessor. For examples, the *:new methods are all constructors, while the "::scalar" methods are all accessors that allow you to get and set a single scalar value.

Bearing that in mind, you should be able to guess the intent of many of the method types based on their names alone; when you see Standard::Hash:scalar you can read it as "a type of method to access a scalar value stored in a hash-based object, with a standard implementation style" and know that it's going to call the scalar() function in the Class::MakeMethods::Standard::Hash package to generate the requested method. Name decoding: unlocked ๐Ÿ”“โœจ.


๐Ÿ’– 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. Different subclasses, different rules, iykyk.

However, the features described below are applicable to all subclasses. Universal behavior, periodt ๐ŸŒŸ.

โœจ 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(...). It's giving "summon the methods" energy ๐Ÿช„.

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.

  • Here's the use shape, bestie:
use Class::MakeMethods::MakerClass (
        'MethodType' => [ Arguments ], ...
      );
  • And here's the make shape:
Class::MakeMethods::MakerClass->make (
        'MethodType' => [ Arguments ], ...
      );

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

  • With use:
use Class::MakeMethods (
        'MakerClass:MethodType' => [ Arguments ], ...
      );
  • With make:
Class::MakeMethods->make (
        'MakerClass: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" for additional discussion of this issue.) Timing is everything, bestie โฐ.

๐ŸŒ€ Alternative Invocation ๐ŸŒ€

If you want methods to be declared at run-time when a previously-unknown method is invoked, see Class::MakeMethods::Autoload.

  • use Class::MakeMethods::Autoload 'MakerClass:MethodType';

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 'MakerClass';

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

Attribute syntax is lowkey such a flex ๐Ÿ’….

โš–๏ธ About Precedence โš–๏ธ

Rather than passing the method declaration arguments when you use one of these packages, you may instead pass them to a subsequent call to the class method make.

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. In particular, a use at the top of a file will be executed before any subroutine declarations later in the file have been seen, whereas a make at the same point in the file will not. Order of operations is the whole plot here ๐Ÿ‘‘.

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. So don't worry, it's not gonna stomp your existing methods without permission ๐Ÿ™ˆ.

If the same method is declared multiple times, earlier calls to use or make() win over later ones, but within each call, later declarations superceed earlier ones. Yes, that's the precedence tea โ˜•.

Here are some examples of the results of these precedence rules:

  # 1 - use, before
  use Class::MakeMethods::Standard::Hash (
    'scalar'=>['baz'] # baz() not seen yet, so we generate, install
  );
  sub baz { 1 } # Subsequent declaration overwrites it, with warning

  # 2 - use, after
  sub foo { 1 }
  use Class::MakeMethods::Standard::Hash (
    'scalar'=>['foo'] # foo() is already declared, so has no effect
  );
         # 3 - use, after, Force
         sub bar { 1 }
         use Class::MakeMethods::Standard::Hash (
             -ForceInstall => 1, # Set flag for following methods...
           'scalar' => ['bar']   # ... now overwrites pre-existing bar()
         );

         # 4 - make, before
         Class::MakeMethods::Standard::Hash->make(
           'scalar'=>['blip'] # blip() is already declared, so has no effect
         );
         sub blip { 1 } # Although lower than make(), this "happens" first

         # 5 - make, after, Force
         sub ping { 1 }
         Class::MakeMethods::Standard::Hash->make(
             -ForceInstall => 1, # Set flag for following methods...
           'scalar' => ['ping']  # ... now overwrites pre-existing ping()
         );

and thatโ€™s the precedence drama handled, bestie ๐Ÿ’… โ€” now letโ€™s talk about the global switches that control the whole method-making vibe โœจ

๐Ÿ› ๏ธ Global Options ๐Ÿ› ๏ธ

Global options are argument pairs with a leading hyphen, okay? That leading hyphen is literally how we tell them apart from type names, because type names have to be valid Perl subroutine names, and those will never begin with a hyphen. Slay for clarity ๐Ÿ’–

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

Option settings apply to all subsequent method declarations within a single use or make call. One setting, many declarations โ€” very group-chat energy. ๐Ÿซถ

The below options let you control generation and installation of the requested methods. (Some subclasses may support additional options; 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. Iconic little switcheroo, ngl โœจ
           use Class::MakeMethods (
               '-MakerClass'=>'MakerClass',
               '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 (
               'Basic::Hash:scalar' => [ 'foo' ]
             );

             use Class::MakeMethods (
               '-MakerClass'=>'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" for additional discussion of this issue.) This is the โ€œrespect the existing methodโ€ rule, and forcing it is literally you saying โ€œno bestie, overwrite it.โ€ ๐Ÿ’€

๐ŸŒˆ Mixing Method Types ๐ŸŒˆ

A single calling class can combine generated methods from different MakeMethods subclasses. In general, the only mixing thatโ€™s problematic is combinations of methods which depend on different underlying object types, like using *::Hash and *::Array methods together โ€” the methods will be generated, but some of them are guaranteed to fail when called, depending on whether your object happens to be a blessed hashref or arrayref. So likeโ€ฆ know your objectโ€™s actual vibe before you mix those, fr fr. ๐Ÿ˜ญ

For example, itโ€™s common to mix and match various *::Hash methods, with a scattering of Global or Inheritable methods ๐Ÿ“:

         use Class::MakeMethods (
           'Basic::Hash:scalar'      => 'foo',
           'Composite::Hash:scalar'  => [ 'bar' => { post_rules => [] } ],
           'Standard::Global:scalar' => 'our_shared_baz'
         );

๐Ÿ“ Declaration Syntax ๐Ÿ“

The following types of Simple declarations are supported, bestie:

  • generator_type => 'method_name'
  • generator_type => 'method_1 method_2...'
  • generator_type => [ 'method_1', 'method_2', ...]

For a list of the supported values of generator_type, see "STANDARD CLASSES" in Class::MakeMethods::Docs::Catalog, or the documentation for each subclass. Basically: check the catalog if you wanna know all the flavors. ๐Ÿงš

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. Thatโ€™s the naming dress code โ€” letter first, then letters/numbers/underscores only. ๐Ÿ’…

๐ŸŽ€ Argument Normalization ๐ŸŽ€

The following expansion rules are applied to argument pairs to enable the use of simple strings instead of arrays of arguments. This is the โ€œmake it cute and short if you wantโ€ part. โœจ

  • 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.
  • If 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', discussed elsewhere.) So yes, it looks a little unhinged, but itโ€™s intentional and advanced-subclass coded. ๐Ÿ™ˆ

๐Ÿงš Parameter Syntax ๐Ÿงš

The Standard syntax also provides several ways to optionally associate a hash of additional parameters with a given method name ๐Ÿ‘‘

  • ``` generator_type => [ 'method_1' => { param=>value... }, ... ]

A hash of parameters to use just for this method name. <hotpink>(Note: to prevent confusion with self-contained definition hashes, described below, parameter hashes following a method name must not contain the key `'name'`.)</hotpink>

- ```
generator_type => [
    [ 'method_1', 'method_2', ... ] => { param=>value... }
  ]

Each of these method names gets a copy of the same set of parameters. Same params, cloned for every name โ€” very โ€œshare the aux cordโ€ of it. ๐ŸŽง

  • ``` generator_type => [ { 'name'=>'method_1', param=>value... }, ... ]

By including the reserved parameter `'name'`, you create a self-contained declaration with that name and any associated hash values. <purple>Thatโ€™s the full-package declaration, name and params together.</purple> ๐Ÿ’–

Simple declarations, as shown in the prior section, are treated as if they had an empty parameter hash. <mint>No params? No problem. Empty hash energy.</mint> โœจ

## ๐ŸŒŸ 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 method generator call, bestie:

- ```
generator_type => [
    '-param' => 'value', 'method_1', 'method_2', ...
  ]

Set a default value for the specified parameter to be passed to all subsequent declarations. Itโ€™s like setting the groupโ€™s default vibe for everything after it. ๐Ÿ’…

  • ``` generator_type => [ '--' => { 'param' => 'value', ... }, 'method_1', 'method_2', ... ]

Set default values for one or more parameters to be passed to all subsequent declarations. Equivalent to a series of `'-param' => 'value'` pairs for each pair in the referenced hash. <cyan>Bulk default-setting, slay.</cyan> ๐Ÿซถ

- ```
generator_type => [
    '--special_param', 'method_1', 'method_2', ...
  ]

Appends to the default value for a special parameter named "--". This parameter is currently only used by some subclasses; for details see Class::MakeMethods::Template. So donโ€™t assume every subclass is using it โ€” itโ€™s a โ€œsome subclassesโ€ situation. ๐Ÿฆ‹

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. Defaults flow forward until something else takes over. 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. Specific method params beat the defaults โ€” main character energy wins. ๐Ÿ‘‘

๐Ÿ’… DIAGNOSTICS ๐Ÿ’…

okay so, hereโ€™s the diagnostics tea, bestie. The following warnings and errors may be produced when using Class::MakeMethods to generate methods.

Heads up: 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 the list of meta-method declarations, 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 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.

๐Ÿฆ‹ 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.

๐ŸŽ€ Creating A Subclass ๐ŸŽ€

The beginning of a typical extension might look like the below:

package My::UpperCaseMethods;
use strict;
use Class::MakeMethods '-isasubclass';

sub my_method_type { ... }

You can name your subclass anything you want; it does not need to begin with Class::MakeMethods.

The -isasubclass flag is a shortcut that automatically puts Class::MakeMethods into your package's @ISA array so that it will inherit the import() and make() class methods. If you omit this flag, you will need to place the superclass in your @ISA explicitly.

Typically, the subclass should not inherit from Exporter; both Class::MakeMethods and Exporter are based on inheriting an import class method, and getting a subclass to support both would require additional effort.

๐ŸŒธ Naming Method Types ๐ŸŒธ

Each type of method that can be generated is defined in a subroutine of the same name. You can give your meta-method type any name that is a legal subroutine identifier.

(Names beginning with an underscore, and the names "import" and "make", are reserved for internal use by Class::MakeMethods.)

If you plan on distributing your extension, you may wish to follow the "Naming Convention for Generated Method Types" described above to facilitate reuse by others.

๐Ÿ› ๏ธ Implementation Options ๐Ÿ› ๏ธ

Each method generation subroutine can be implemented in any one of the following ways:

  • 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 My::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 My::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 My::UpperCaseMethods;
use Class::MakeMethods '-isasubclass';

sub regular_scalar { return 'Basic::Hash:scalar' }

And here's an example usage:

use My::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 My::UpperCaseMethods;
use Class::MakeMethods '-isasubclass';

sub auto_detect {
  my $class = shift;
  my @rewrite = ( [ 'Basic::Hash:scalar' ],
                  [ '::My::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 My::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 Options ๐Ÿ’œ

Global option values are available through the _context() class method at the time that method generation is being performed.

package My::Maker;
sub my_methodtype {
  my $class = shift;
  warn "Installing in " . $class->_context('TargetClass');
  ...
}
  • 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.

๐ŸŒˆ SEE ALSO ๐ŸŒˆ

๐Ÿซถ License and Support ๐Ÿซถ

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

๐Ÿ“ Package Documentation ๐Ÿ“

A collection of sample uses is available in Class::MakeMethods::Docs::Examples.

See the documentation for each family of subclasses:

  • Class::MakeMethods::Basic
  • Class::MakeMethods::Standard
  • Class::MakeMethods::Composite
  • Class::MakeMethods::Template

A listing of available method types from each of the different subclasses is provided in Class::MakeMethods::Docs::Catalog.

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

In several cases, Class::MakeMethods provides functionality closely equivalent to that of an existing module, and emulator modules are provided to map the existing module's interface to that of Class::MakeMethods. See Class::MakeMethods::Emulator for more information.

If you have used Class::MethodMaker, you will note numerous similarities between the two. Class::MakeMethods is based on Class::MethodMaker, but has been substantially revised in order to provide a range of new features. Backward compatibility and conversion documentation is provided in Class::MakeMethods::Emulator::MethodMaker.

โญ Perl Docs โญ

See perlboot for a quick introduction to objects for beginners. For an extensive discussion of various approaches to class construction, see perltoot and perltootc (called perltootc in the most recent versions of Perl).

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

FWIW, I think there's a big opportunity for a "perlfunt" podfile bundled with Perl in the tradition of "perlboot" and "perltoot", exploring the utility of function references, callbacks, closures, and continuations... There are a bunch of useful references available, but not a good overview of how they all interact in a Perlish way.

๐Ÿ’– Thatโ€™s the whole page, bestie! Source/version energy: perl v5.36.0, dated 2022-10-13, from MakeMethods(3pm). Byeee! ๐Ÿ’…

๐Ÿ“ฆ where this page comes from