MakeMe...emplate(3pm)
π NAME
Class::MakeMethods::Template β Extensible code templates. Okay so this is the MakeMe...emplate(3pm) manual page, bestie, coming at you from the User Contributed Perl Documentation pile π.
β¨ 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
So like, if you go compare the source code of some of those closure-generating methods that other subclasses of Class::MakeMethods hand you β think the "hash" accessors from the various Standard::* subclasses β you will literally notice a fair amount of duplication. This module is the glow-up: it gives you a way to assemble common pieces of code so it's way easier to support the maintenance of much larger libraries of generated methods. No cap β¨.
πΈ DESCRIPTION
This module extends the Class::MakeMethods framework by providing an abstract superclass for extensible code-templating method generators. Iconic behavior, honestly π.
Common types of methods get 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 let you get and set individual scalar values. Obsessed with the reuse potential π¦.
Those 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. It's giving inheritance, but make it cute π.
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. Main character energy for meta-methods, fr fr π .
π 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. Slay π«.
You can also omit the arguments to use and instead make methods at runtime by passing the declarations to a subsequent call to make(). Very runtime of you π«Ά.
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. Yes bestie, that's the rule π.
You can install methods in a different package by passing -TargetClass => package as your first arguments to use or make(). Package-hopping, but make it legal β¨.
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. Go look, it's a whole catalog moment π.
For each method name you provide, a subroutine of the indicated type will be generated and installed under that name in your module. Automatic install, no manual labor π.
Method names should start with a letter, followed by zero or more letters, numbers, or underscores. Keep it valid, bestie β .
π Standard Declaration Syntax
The Standard syntax provides several ways to optionally associate a hash of additional parameters with a given method name. Options, options, options π
.
generator_type => [ "name_1" => { param=>value... }, ... ]
A hash of parameters to use just for this method name. So specific, so special π.
(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. Sharing is caring π«Ά.
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. Self-contained queen behavior π.
Basic declarations, as described above, are treated as having an empty parameter hash. Simple, clean, iconic πΈ.
π 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. Defaults are a love language π.
'--' => { '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. Bulk default energy β¨.
'--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. Scroll down, bestie π
.
'--modifier_name'
Select a global behavior modifier, such as '--private' or '--protected'.
For more information about modifiers, see "Selecting Modifiers" below. Modifier lore incoming π¦.
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. Override culture, but make it intentional π.
β¨ PARAMETER REFERENCE β¨
Okay so bestie, every meta-method gets its own lil hash to keep its parameters and optional info in. Think of it as the method's personal diary. π
Heads up though: you can not override parameters on a per-object level. Like, ever. Not even a little. That's just how it is, no cap. π
π«Ά Special Parameters
These bad boys are either pre-defined or have a Special Meaning (iconic behavior):
nameβ the primary name of the meta-method. Lowkey important: the subroutines actually installed into the calling package might get different names, depending on whatever rules the interface specifies. So don't assume, k? πinterfaceβ the name of a predefined interface, or a reference to a custom interface, that you want to use for this meta-method. See "Selecting Interfaces" below, it's giving whole section. β¨modifierβ the names of one or more predefined modifier flags. See "Selecting Modifiers" below. π¦
πΈ Informative Parameters
These get set automatically when your meta-method is declared β you don't do a thing, they just appear:
target_classβ the class that requested the meta-method, and the one its subroutines will get installed into. πtemplate_nameβ theClass::MakeMethods::Templatemethod used for this declaration.template_classβ theClass::MakeMethods::Templatesubclass used for this declaration.
π¦ Other Parameters
Specific subclasses and template types support their own extra parameters. Fancy.
But ngl, you generally should not just arbitrarily slap additional parameters onto a meta-method unless you actually know they don't conflict with any parameters already defined or used by that meta-method. Like, be careful, bestie. π
π Parameter Expansion
Here's where it gets cute. If a parameter specification contains '*', it gets replaced with the primary method name. Iconic substitution moment.
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 / ];
(Peep Class::MakeMethods::Template::Hash for the deets on the hash_key parameter. π)
And if a parameter specification contains '*{param}', it gets replaced with the value of that parameter. Chef's kiss.
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 interface specifies one or more methods to be installed in your package, plus the method names to use. Check the documentation for specific templates for the full list of which interfaces they define β it's giving required reading. π
You can specify an interface for a single method by passing it an interface parameter:
'interface_name'β picks a predefined interface. Slay.
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 method named q. (There are no set or clear methods, so any value would have to be placed in the hash by other means. Lowkey mysterious. π)
use Class::MakeMethods::Template::Hash (
'scalar' => [ 'q' => { interface=>'get' } ]
);
{ 'subroutine_name_pattern' => 'behavior_name', ... }β a custom interface. It's a hash-ref that maps subroutine names to the associated behaviors. Any'*'characters insubroutine_name_patternget replaced with the declared method name. Match made in heaven. β¨
For example, the below declaration 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. Like, whole different personality. π
Example: the following defines a method g, which if called with an argument appends to the current value rather than overwriting it:
use Class::MakeMethods::Template::Hash
'string' => [ '--get_concat', 'g' ];
A named interface can also be specified as a default in the argument list with a leading '--' followed by the interface's name. Vibes only.
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 this way affects all meta-methods that follow it, until another interface is selected or you hit the end of the array. To get back to the original names, request the 'default' interface. It's like a vibe reset. π
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. Yes, all of them. Main character energy.
use Class::MakeMethods::Template::Hash
'scalar' => [ 'a', '--protected' => 'b', --private' => 'c' ];
- Method
bcroaks if it's called from outside of the current package or its subclasses. π - Method
ccroaks if it's called from outside of the current package. Even more exclusive.
See the documentation for each template to learn which modifiers it supports. Not every template is gonna match your vibe. π¦
β Runtime Parameter Access
If the meta-method is defined using an interface which includes the attributes method, you get run-time access to meta-method parameters. Hello?? That's so cool actually.
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 π
okay so you wanna build your own method-generator templates? iconic. hereβs the whole outline, and yes, weβre keeping every detail because thatβs the vibe. β¨
π οΈ 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:
interfaceβ Naming styles (see"Defining Interfaces", below)paramsβ Default parameters for meta-methods declared with this template (see"Default Parameters", below)behaviorβ Method recipes (see"Defining Behaviors", below)code_exprβ Bits of code used by the behaviors
π§Έ 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 overridden by interface '-params', described below, and by 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 beginning 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-basespecification in 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 suppresses 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 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 π
okay bestie, you're at the end of the page but the lore does not stop here, there's literally a whole extended universe π
Class::MakeMethodsβ this is the mothership πΈ head there for all the general tea about this distribution. general information, the big picture, the whole vibe.Class::MakeMethods::Examplesβ this one's the mood board β¨ it's got actual illustrations of what you can do with this package. like, real examples. go look, it's giving inspiration.Class::MakeMethods::Docs::ReadMeβ the boring-but-important one π everything about distribution, installation, support, copyright and license info lives here. yes all of it. go read it, i'm serious.
and that's a wrap on the whole page, bestie π«Ά you made it to the very end, i'm so proud π this is MakeMe...emplate(3pm) from perl v5.36.0, dated 2022-10-13 β go forth and make methods, you absolute icon ππΈπ
π¦ where this page comes from
- ubuntu noble: libclass-makemethods-perl 1.01-7 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libclass-makemethods-perl 1.01-7 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libclass-makemethods-perl 1.01-7 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms