1MakeMethods::Template(3U)ser Contributed Perl DocumentatiMoankeMethods::Template(3)
2
3
4

NAME

6       Class::MakeMethods::Template - Extensible code templates
7

SYNOPSIS

9         package MyObject;
10         use Class::MakeMethods::Template::Hash (
11           'new'       => 'new',
12           'string'    => 'foo',
13           'number'    => 'bar',
14         );
15
16         my $obj = MyObject->new( foo => "Foozle", bar => 23 );
17         print $obj->foo();
18         $obj->bar(42);
19

MOTIVATION

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

DESCRIPTION

29       This module extends the Class::MakeMethods framework by providing an
30       abstract superclass for extensible code-templating method generators.
31
32       Common types of methods are generalized into template definitions.  For
33       example, "Template::Generic"'s "new" provides a template for methods
34       that create object instances, while "Template::Generic"'s "scalar" is a
35       template for methods that allow you to get and set individual scalar
36       values.
37
38       Thse definitions are then re-used and modified by various template sub‐
39       classes. For example, the "Template::Hash" subclass supports blessed-
40       hash objects, while the "Template::Global" subclass supports shared
41       data; each of them includes an appropriate version of the "scalar"
42       accessor template for those object types.
43
44       Each template defines one or more behaviors, individual methods which
45       can be installed in a calling package, and interfaces, which select
46       from those behaviours and indicate the names to install the methods
47       under.
48
49       Each individual meta-method defined by a calling package requires a
50       method name, and may optionally include other key-value parameters,
51       which can control the operation of some meta-methods.
52

USAGE

54       Class::MakeMethods Calling Conventions
55
56       When you "use" this package, the method declarations you provide as
57       arguments cause subroutines to be generated and installed in your mod‐
58       ule.
59
60       You can also omit the arguments to "use" and instead make methods at
61       runtime by passing the declarations to a subsequent call to "make()".
62
63       You may include any number of declarations in each call to "use" or
64       "make()". If methods with the same name already exist, earlier calls to
65       "use" or "make()" win over later ones, but within each call, later dec‐
66       larations superceed earlier ones.
67
68       You can install methods in a different package by passing "-TargetClass
69       => package" as your first arguments to "use" or "make".
70
71       See Class::MakeMethods for more details.
72
73       Passing Parameters
74
75       The following types of Basic declarations are supported:
76
77       ·   generator_type => "method_name"
78
79       ·   generator_type => "name_1 name_2..."
80
81       ·   generator_type => [ "name_1", "name_2", ...]
82
83       See "TEMPLATE CLASSES" in Class::MakeMethods::Docs::Catalog for a list
84       of the supported values of generator_type.
85
86       For each method name you provide, a subroutine of the indicated type
87       will be generated and installed under that name in your module.
88
89       Method names should start with a letter, followed by zero or more let‐
90       ters, numbers, or underscores.
91
92       Standard Declaration Syntax
93
94       The Standard syntax provides several ways to optionally associate a
95       hash of additional parameters with a given method name.
96
97       ·   generator_type => [ "name_1" => { param=>value... }, ... ]
98
99           A hash of parameters to use just for this method name.
100
101           (Note: to prevent confusion with self-contained definition hashes,
102           described below, parameter hashes following a method name must not
103           contain the key 'name'.)
104
105       ·   generator_type => [ [ "name_1", "name_2", ... ] => {
106           param=>value... } ]
107
108           Each of these method names gets a copy of the same set of parame‐
109           ters.
110
111       ·   generator_type => [ { "name"=>"name_1", param=>value... }, ... ]
112
113           By including the reserved parameter "name", you create a self con‐
114           tained declaration with that name and any associated hash values.
115
116       Basic declarations, as described above, are treated as having an empty
117       parameter hash.
118
119       Default Parameters
120
121       A set of default parameters to be used for several declarations may be
122       specified using any of the following types of arguments to a Template
123       method generator call:
124
125       ·   '-param' => 'value'
126
127           Set a default value for the specified parameter.
128
129       ·   '--' => { 'param' => 'value', ... }
130
131           Set default values for one or more parameters. Equivalent to a
132           series of '-param' => 'value' pairs for each pair in the referenced
133           hash.
134
135       ·   '--special_param_value'
136
137           Specifies a value for special parameter; the two supported parame‐
138           ter types are:
139
140           -   '--interface_name'
141
142               Select a predefined interface; equivalent to '-interface'=>
143               'interface_name'.
144
145               For more information about interfaces, see "Selecting Inter‐
146               faces" below.
147
148           -   '--modifier_name'
149
150               Select a global behavior modifier, such as '--private' or
151               '--protected'.
152
153               For more information about modifiers, see "Selecting Modifiers"
154               below.
155
156       Parameters set in these ways are passed to each declaration that fol‐
157       lows it until the end of the method-generator argument array, or until
158       overridden by another declaration. Parameters specified in a hash for a
159       specific method name, as discussed above, will override the defaults of
160       the same name for that particular method.
161

PARAMETER REFERENCE

163       Each meta-method is allocated a hash in which to store its parameters
164       and optional information.
165
166       (Note that you can not override parameters on a per-object level.)
167
168       Special Parameters
169
170       The following parameters are pre-defined or have a special meaning:
171
172       ·   name
173
174           The primary name of the meta-method. Note that the subroutines
175           installed into the calling package may be given different names,
176           depending on the rules specified by the interface.
177
178       ·   interface
179
180           The name of a predefined interface, or a reference to a custom
181           interface, to use for this meta-method. See "Selecting Interfaces",
182           below.
183
184       ·   modifier
185
186           The names of one or more predefined modifier flags. See "Selecting
187           Modifiers", below.
188
189       Informative Parameters
190
191       The following parameters are set automatically when your meta-method is
192       declared:
193
194       ·   target_class
195
196           The class that requested the meta-method, into which its subrou‐
197           tines will be installed.
198
199       ·   template_name
200
201           The Class::MakeMethods::Template method used for this declaration.
202
203       ·   template_class
204
205           The Class::MakeMethods::Template subclass used for this declara‐
206           tion.
207
208       Other Parameters
209
210       Specific subclasses and template types provide support for additional
211       parameters.
212
213       Note that you generally should not arbitrarily assign additional param‐
214       eters to a meta-method unless you know that they do not conflict with
215       any parameters already defined or used by that meta-method.
216
217       Parameter Expansion
218
219       If a parameter specification contains '*', it is replaced with the pri‐
220       mary method name.
221
222       Example: The following defines counter (*, *_incr, *_reset) meta-meth‐
223       ods j and k, which use the hash keys j_index and k_index to fetch and
224       store their values.
225
226         use Class::MakeMethods::Template::Hash
227           counter => [ '-hash_key' => '*_index', qw/ j k / ];
228
229       (See Class::MakeMethods::Template::Hash for information about the
230       "hash_key" parameter.)
231
232       If a parameter specification contains '*{param}', it is replaced with
233       the value of that parameter.
234
235       Example: The following defines a Hash scalar meta-method which will
236       store its value in a hash key composed of the defining package's name
237       and individual method name, such as "$self->{MyObject-foo}":
238
239         use Class::MakeMethods::Template::Hash
240           'scalar' => [ '-hash_key' => '*{target_class}-*{name}', qw/ l / ];
241
242       Selecting Interfaces
243
244       Each template provides one or more predefined interfaces, each of which
245       specifies one or more methods to be installed in your package, and the
246       method names to use. Check the documentation for specific templates for
247       a list of which interfaces they define.
248
249       An interface may be specified for a single method by providing an
250       'interface' parameter:
251
252       ·   'interface_name'
253
254           Select a predefined interface.
255
256           Example: Instead of the normal Hash scalar method named x, the fol‐
257           lowing creates methods with "Java-style" names and behaviors, getx
258           and setx.
259
260             use Class::MakeMethods::Template::Hash
261               'scalar' => [ 'x' => { interface=>'java' } ];
262
263           (See "scalar" in Class::MakeMethods::Template::Generic for a
264           description of the "java" interface.)
265
266       ·   'behavior_name'
267
268           A simple interface consisting only of the named behavior.
269
270           For example, the below declaration creates a read-only methods
271           named q. (There are no set or clear methods, so any value would
272           have to be placed in the hash by other means.)
273
274             use Class::MakeMethods::Template::Hash (
275               'scalar' => [ 'q' => { interface=>'get' } ]
276             );
277
278       ·   {  'subroutine_name_pattern' => 'behavior_name', ... }
279
280           A custom interface consists of a hash-ref that maps subroutine
281           names to the associated behaviors. Any "*" characters in subrou‐
282           tine_name_pattern are replaced with the declared method name.
283
284           For example, the below delcaration creates paired get_w and set_w
285           methods:
286
287             use Class::MakeMethods::Template::Hash (
288               'scalar' => [ 'w' => { interface=> { 'get_*'=>'get', 'set_*'=>'set' } } ]
289             );
290
291       Some interfaces provide very different behaviors than the default
292       interface.
293
294       Example: The following defines a method g, which if called with an
295       argument appends to, rather than overwriting, the current value:
296
297         use Class::MakeMethods::Template::Hash
298           'string' => [ '--get_concat', 'g' ];
299
300       A named interface may also be specified as a default in the argument
301       list with a leading '--' followed by the interface's name.
302
303       Example: Instead of the normal Hash scalar methods (named x and
304       clear_x), the following creates methods with "Java-style" names and
305       behaviors (getx, setx).
306
307         use Class::MakeMethods::Template::Hash
308           'scalar' => [ '--java', 'x'  ];
309
310       An interface set in this way affects all meta-methods that follow it
311       until another interface is selected or the end of the array is reached;
312       to return to the original names request the 'default' interface.
313
314       Example: The below creates "Java-style" methods for e and f, "normal
315       scalar" methods for g, and "Eiffel-style" methods for h.
316
317         use Class::MakeMethods::Template::Hash
318           'scalar' => [
319             '--java'=> 'e', 'f',
320             '--default'=> 'g',
321             '--eiffel'=> 'h',
322           ];
323
324       Selecting Modifiers
325
326       You may select modifiers, which will affect all behaviors.
327
328         use Class::MakeMethods::Template::Hash
329             'scalar' => [ 'a', '--protected' => 'b', --private' => 'c' ];
330
331       Method b croaks if it's called from outside of the current package or
332       its subclasses.
333
334       Method c croaks if it's called from outside of the current package.
335
336       See the documentation for each template to learn which modifiers it
337       supports.
338
339       Runtime Parameter Access
340
341       If the meta-method is defined using an interface which includes the
342       attributes method, run-time access to meta-method parameters is avail‐
343       able.
344
345       Example: The following defines a counter meta-method named y, and then
346       later changes the 'join' parameter for that method at runtime.
347
348         use Class::MakeMethods ( get_concat => 'y' );
349
350         y_attributes(undef, 'join', "\t" )
351         print y_attributes(undef, 'join')
352

EXTENDING

354       You can create your own method-generator templates by following the
355       below outline.
356
357       Mechanisms
358
359       Dynamic generation of methods in Perl generally depends on one of two
360       approaches: string evals, which can be as flexible as your string-
361       manipulation functions allow, but are run-time resource intensive; or
362       closures, which are limited by the number of subroutine constructors
363       you write ahead of time but which are faster and smaller than evals.
364
365       Class::MakeMethods::Template uses both of these approaches: To generate
366       different types of subroutines, a simple text-substitution mechanism
367       combines bits of Perl to produce the source code for a subroutine, and
368       then evals those to produce code refs. Any differences which can be
369       handled with only data changes are managed at the closure layer; once
370       the subroutines are built, they are repeatedly bound as closures to
371       hashes of parameter data.
372
373       Code Generation
374
375       A substitution-based "macro language" is used to assemble code strings.
376       This happens only once per specific subclass/template/behavior combina‐
377       tion used in your program. (If you have disk-caching enabled, the tem‐
378       plate interpretation is only done once, and then saved; see below.)
379
380       There are numerous examples of this within the Generic interface and
381       its subclasses; for examples, look at the following methods: Univer‐
382       sal:generic, Generic:scalar, Hash:generic, and Hash:scalar.
383
384       See Class::MakeMethods::Utility::TextBuilder for more information.
385
386       Template Definitions
387
388       Template method generators are declared by creating a subroutine that
389       returns a hash-ref of information about the template. When these sub‐
390       routines are first called, the template information is filled in with
391       imported and derived values, blessed as a Class::MakeMethods::Template
392       object, and cached.
393
394       Each "use" of your subclass, or call to its "make", causes these
395       objects to assemble the requested methods and return them to
396       Class::MakeMethods for installation in the calling package.
397
398       Method generators defined this way will have support for parameters,
399       custom interfaces, and the other features discussed above.
400
401       (Your module may also use the "Aliasing" and "Rewriting" functionality
402       described in "EXTENDING" in Class::MakeMethods.)
403
404       Definition hashes contain several types of named resources in a second
405       level of hash-refs under the following keys:
406
407       ·   interface - Naming styles (see "Defining Interfaces", below)
408
409       ·   params - Default parameters for meta-methods declared with this
410           template (see "Default Parameters", below)
411
412       ·   behavior - Method recipes (see "Defining Behaviors", below)
413
414       ·   code_expr - Bits of code used by the behaviors
415
416       Minimum Template Definition
417
418       You must at least specify one behavior; all other information is
419       optional.
420
421       Class::MakeMethods will automatically fill in the template name and
422       class as 'template_name' and 'template_class' entries in the version of
423       your template definition hash that it caches and uses for future execu‐
424       tion.
425
426       For example a simple sub-class that defines a method type
427       upper_case_get_set might look like this:
428
429         package Class::MakeMethods::UpperCase;
430         use Class::MakeMethods '-isasubclass';
431
432         sub uc_scalar {
433           return {
434             'behavior' => {
435               'default' => sub {
436                 my $m_info = $_[0];
437                 return sub {
438                   my $self = shift;
439                   if ( scalar @_ ) {
440                     $self->{ $m_info->{'name'} } = uc( shift )
441                   } else {
442                     $self->{ $m_info->{'name'} };
443                   }
444                 }
445               },
446             }
447           }
448         }
449
450       And a caller could then use it to generate methods in their package by
451       invoking:
452
453         Class::MakeMethods::UpperCase->make( 'uc_scalar' => [ 'foo' ] );
454
455       Default Parameters
456
457       Each template may include a set of default parameters for all declara‐
458       tions as "params => hash_ref".
459
460       Template-default parameters can be overrridden by interface '-params',
461       described below, and and method-specific parameters, described above.
462
463       Defining Interfaces
464
465       Template definitions may have one or more interfaces, including the
466       default one, named 'default', which is automatically selected if
467       another interface is not requested. (If no default interface is pro‐
468       vided, one is constructed, which simply calls for a behavior named
469       default.)
470
471       Most commonly, an interface is specified as a hash which maps one or
472       more subroutine names to the behavior to use for each. The interface
473       subroutine names generally contain an asterisk character, '*', which
474       will be replaced by the name of each meta-method.
475
476       Example: The below defines methods e_get, e_set, and e_clear.
477
478         use Class::MakeMethods::Template::Hash
479           'scalar' => [
480             -interface=>{ '*_clear'=>clear, '*_get'=>'get', '*_set'=>'set' }, 'e'
481           ];
482
483       If the provided name does not contain an asterisk, it will not be modi‐
484       fied for individual meta-methods; for examples, see the bit_fields
485       method generated by Generic bits, and the DESTROY method generated by
486       InsideOut meta-methods.
487
488       In addition to the name-to-behavior correspondences described above,
489       interfaces may also contain additional entries with keys begining with
490       the '-' character which are interpreted as follows:
491
492       ·   "-params => hash_ref"
493
494           Interfaces may include a '-params' key and associated reference to
495           a hash of default parameters for that interface.
496
497       ·   "-base => interface_name"
498
499           Interfaces can be based on previously existing ones by including a
500           -base specification in the the hash. The base value should contain
501           one or more space-separated names of the interfaces to be included.
502
503           Example: The below defines methods getG, setG, and clearG.
504
505             use Class::MakeMethods::Template::Hash
506               'scalar' => [
507                 -interface => { -base=>'java', 'clear*'=>'clear' }, qw/ G /
508               ];
509
510           If multiple interfaces are included in the -base specification and
511           specify different behaviors for the same subroutine name, the later
512           ones will override the earlier. Names which appear in the base
513           interface can be overridden by providing a new value, or a name can
514           be removed by mapping it to undef or the empty string.
515
516           Example: The following defines a get-set meta-method h, but
517           supresses the clear_h method:
518
519             use Class::MakeMethods::Template::Hash
520               'scalar' => [
521                 -interface => { -base=>'with_clear', 'clear_*'=>'' }, qw/ h /
522               ];
523
524       Defining Behaviors
525
526       Behaviors can be provided as text which is eval'd to form a closure-
527       generating subroutine when it's first used; $self is automatically
528       defined and assigned the value of the first argument.
529
530             'behavior' => {
531               'default' => q{
532                   if ( scalar @_ ) { $self->{ $m_info->{'name'} } = uc shift }
533                   $self->{ $m_info->{'name'} };
534               },
535             }
536
537       A simple substitution syntax provides for macro interpretation with
538       definition strings. This functionality is currently undocumented; for
539       additional details see the _interpret_text_builder function in
540       Class::MakeMethods, and review the code_expr hashes defined in
541       Class::MakeMethods::Generic.
542
543       Importing
544
545       You can copy values out of other template definitions by specifying an
546       '-import' key and corresponding hash reference. You can specify an
547       -import for inside any of the template definition sub-hashes.  If no
548       -import is specified for a subhash, and there is a top-level -import
549       value, it is used instead.
550
551       Inside an -import hash, provide "TemplateClass:type" names for each
552       source you wish to copy from, and the values to import, which can be a
553       string, a reference to an array of strings, or '*' to import everything
554       available. (The order of copying is not defined.)
555
556       Example: The below definition creates a new template which is identical
557       to an existing one.
558
559         package Class::MakeMethods::MyMethods;
560         sub scalarama {
561           { -import => { 'Template::Hash:scalar' => '*' } }
562         }
563
564       Values that are already set are not modified, unless they're an array
565       ref, in which case they're added to.
566
567       Example:
568
569         package Class::MakeMethods::MyMethods;
570         sub foo_method {
571           { 'behavior' => {
572             '-init' => [ sub {  warn "Defining foo_method $_[0]->{'name'}" } ],
573             'default' => q{ warn "Calling foo_method behavior" }.
574           } }
575         }
576         sub bar_method {
577           { 'behavior' => {
578             -import => { 'MyMethods:foo_method' => '*' },
579             '-init' => [ sub {  warn "Defining bar_method $_[0]->{'name'}" } ],
580             'default' => q{ warn "Calling bar_method behavior" }.
581           } }
582         }
583
584       In this case, the bar_method ends up with an array of two '-init' sub‐
585       routines, its own and the imported one, but only its own default behav‐
586       ior.
587
588       Modifying Existing Templates
589
590       You can over-write information contained in template definitions to
591       alter their subsequent behavior.
592
593       Example: The following extends the Hash:scalar template definition by
594       adding a new interface, and then uses it to create scalar accessor
595       methods named access_p and access_q that get and set values for the
596       hash keys 'p' and 'q':
597
598         Class::MakeMethods::Template::Hash->named_method('scalar')->
599                 {'interface'}{'frozzle'} = { 'access_*'=>'get_set' };
600
601         package My::Object;
602         Class::MakeMethods::Template::Hash->make( 'scalar' => [ --frozzle => qw( p q ) ] );
603
604         $object->access_p('Potato');    # $object->{p} = 'Potato'
605         print $object->access_q();      # print $object->{q}
606
607       Note that this constitutes "action at a distance" and will affect sub‐
608       sequent use by other packages; unless you are "fixing" the current
609       behavior, you are urged to create your own template definition which
610       imports the base behavior of the existing template and overrides the
611       information in question.
612
613       Example: The following safely declares a new version of Hash:scalar
614       with the desired additional interface:
615
616         package My::Methods;
617
618         sub scalar {
619           {
620             -import => { 'Template::Hash:scalar' => '*' } ,
621             interface => { 'frozzle' => { 'access_*'=>'get_set' } },
622           }
623         }
624
625         package My::Object;
626         My::Methods->make( 'scalar' => [ --frozzle => qw( p q ) ] );
627
628       Disk Caching
629
630       To enable disk caching of generated code, create an empty directory and
631       pass it to the DiskCache package:
632
633         use Class::MakeMethods::Utility::DiskCache qw( /my/code/dir );
634
635       This has a mixed effect on performance, but has the notable advantage
636       of letting you view the subroutines that are being generated by your
637       templates.
638
639       See Class::MakeMethods::Utility::DiskCache for more information.
640

SEE ALSO

642       See Class::MakeMethods for general information about this distribution.
643
644       See Class::MakeMethods::Examples for some illustrations of what you can
645       do with this package.
646
647       For distribution, installation, support, copyright and license informa‐
648       tion, see Class::MakeMethods::Docs::ReadMe.
649
650
651
652perl v5.8.8                       2004-09-06          MakeMethods::Template(3)
Impressum