1MakeMethods::Template(3U)ser Contributed Perl DocumentatiMoankeMethods::Template(3)
2
3
4
6 Class::MakeMethods::Template - Extensible code templates
7
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
21 If you compare the source code of some of the closure-generating
22 methods 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
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
39 subclasses. For example, the "Template::Hash" subclass supports
40 blessed-hash objects, while the "Template::Global" subclass supports
41 shared data; each of them includes an appropriate version of the
42 "scalar" 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
54 Class::MakeMethods Calling Conventions
55 When you "use" this package, the method declarations you provide as
56 arguments cause subroutines to be generated and installed in your
57 module.
58
59 You can also omit the arguments to "use" and instead make methods at
60 runtime by passing the declarations to a subsequent call to "make()".
61
62 You may include any number of declarations in each call to "use" or
63 "make()". If methods with the same name already exist, earlier calls to
64 "use" or "make()" win over later ones, but within each call, later
65 declarations superceed earlier ones.
66
67 You can install methods in a different package by passing "-TargetClass
68 => package" as your first arguments to "use" or "make".
69
70 See Class::MakeMethods for more details.
71
72 Passing Parameters
73 The following types of Basic declarations are supported:
74
75 · generator_type => "method_name"
76
77 · generator_type => "name_1 name_2..."
78
79 · generator_type => [ "name_1", "name_2", ...]
80
81 See "TEMPLATE CLASSES" in Class::MakeMethods::Docs::Catalog for a list
82 of the supported values of generator_type.
83
84 For each method name you provide, a subroutine of the indicated type
85 will be generated and installed under that name in your module.
86
87 Method names should start with a letter, followed by zero or more
88 letters, numbers, or underscores.
89
90 Standard Declaration Syntax
91 The Standard syntax provides several ways to optionally associate a
92 hash of additional parameters with a given method name.
93
94 · generator_type => [ "name_1" => { param=>value... }, ... ]
95
96 A hash of parameters to use just for this method name.
97
98 (Note: to prevent confusion with self-contained definition hashes,
99 described below, parameter hashes following a method name must not
100 contain the key 'name'.)
101
102 · generator_type => [ [ "name_1", "name_2", ... ] => {
103 param=>value... } ]
104
105 Each of these method names gets a copy of the same set of
106 parameters.
107
108 · generator_type => [ { "name"=>"name_1", param=>value... }, ... ]
109
110 By including the reserved parameter "name", you create a self
111 contained declaration with that name and any associated hash
112 values.
113
114 Basic declarations, as described above, are treated as having an empty
115 parameter hash.
116
117 Default Parameters
118 A set of default parameters to be used for several declarations may be
119 specified using any of the following types of arguments to a Template
120 method generator call:
121
122 · '-param' => 'value'
123
124 Set a default value for the specified parameter.
125
126 · '--' => { 'param' => 'value', ... }
127
128 Set default values for one or more parameters. Equivalent to a
129 series of '-param' => 'value' pairs for each pair in the referenced
130 hash.
131
132 · '--special_param_value'
133
134 Specifies a value for special parameter; the two supported
135 parameter types are:
136
137 - '--interface_name'
138
139 Select a predefined interface; equivalent to '-interface'=>
140 'interface_name'.
141
142 For more information about interfaces, see "Selecting
143 Interfaces" below.
144
145 - '--modifier_name'
146
147 Select a global behavior modifier, such as '--private' or
148 '--protected'.
149
150 For more information about modifiers, see "Selecting Modifiers"
151 below.
152
153 Parameters set in these ways are passed to each declaration that
154 follows it until the end of the method-generator argument array, or
155 until overridden by another declaration. Parameters specified in a hash
156 for a specific method name, as discussed above, will override the
157 defaults of the same name for that particular method.
158
160 Each meta-method is allocated a hash in which to store its parameters
161 and optional information.
162
163 (Note that you can not override parameters on a per-object level.)
164
165 Special Parameters
166 The following parameters are pre-defined or have a special meaning:
167
168 · name
169
170 The primary name of the meta-method. Note that the subroutines
171 installed into the calling package may be given different names,
172 depending on the rules specified by the interface.
173
174 · interface
175
176 The name of a predefined interface, or a reference to a custom
177 interface, to use for this meta-method. See "Selecting Interfaces",
178 below.
179
180 · modifier
181
182 The names of one or more predefined modifier flags. See "Selecting
183 Modifiers", below.
184
185 Informative Parameters
186 The following parameters are set automatically when your meta-method is
187 declared:
188
189 · target_class
190
191 The class that requested the meta-method, into which its
192 subroutines will be installed.
193
194 · template_name
195
196 The Class::MakeMethods::Template method used for this declaration.
197
198 · template_class
199
200 The Class::MakeMethods::Template subclass used for this
201 declaration.
202
203 Other Parameters
204 Specific subclasses and template types provide support for additional
205 parameters.
206
207 Note that you generally should not arbitrarily assign additional
208 parameters to a meta-method unless you know that they do not conflict
209 with any parameters already defined or used by that meta-method.
210
211 Parameter Expansion
212 If a parameter specification contains '*', it is replaced with the
213 primary method name.
214
215 Example: The following defines counter (*, *_incr, *_reset) meta-
216 methods j and k, which use the hash keys j_index and k_index to fetch
217 and store their values.
218
219 use Class::MakeMethods::Template::Hash
220 counter => [ '-hash_key' => '*_index', qw/ j k / ];
221
222 (See Class::MakeMethods::Template::Hash for information about the
223 "hash_key" parameter.)
224
225 If a parameter specification contains '*{param}', it is replaced with
226 the value of that parameter.
227
228 Example: The following defines a Hash scalar meta-method which will
229 store its value in a hash key composed of the defining package's name
230 and individual method name, such as "$self->{MyObject-foo}":
231
232 use Class::MakeMethods::Template::Hash
233 'scalar' => [ '-hash_key' => '*{target_class}-*{name}', qw/ l / ];
234
235 Selecting Interfaces
236 Each template provides one or more predefined interfaces, each of which
237 specifies one or more methods to be installed in your package, and the
238 method names to use. Check the documentation for specific templates for
239 a list of which interfaces they define.
240
241 An interface may be specified for a single method by providing an
242 'interface' parameter:
243
244 · 'interface_name'
245
246 Select a predefined interface.
247
248 Example: Instead of the normal Hash scalar method named x, the
249 following creates methods with "Java-style" names and behaviors,
250 getx and setx.
251
252 use Class::MakeMethods::Template::Hash
253 'scalar' => [ 'x' => { interface=>'java' } ];
254
255 (See "scalar" in Class::MakeMethods::Template::Generic for a
256 description of the "java" interface.)
257
258 · 'behavior_name'
259
260 A simple interface consisting only of the named behavior.
261
262 For example, the below declaration creates a read-only methods
263 named q. (There are no set or clear methods, so any value would
264 have to be placed in the hash by other means.)
265
266 use Class::MakeMethods::Template::Hash (
267 'scalar' => [ 'q' => { interface=>'get' } ]
268 );
269
270 · { 'subroutine_name_pattern' => 'behavior_name', ... }
271
272 A custom interface consists of a hash-ref that maps subroutine
273 names to the associated behaviors. Any "*" characters in
274 subroutine_name_pattern are replaced with the declared method name.
275
276 For example, the below delcaration creates paired get_w and set_w
277 methods:
278
279 use Class::MakeMethods::Template::Hash (
280 'scalar' => [ 'w' => { interface=> { 'get_*'=>'get', 'set_*'=>'set' } } ]
281 );
282
283 Some interfaces provide very different behaviors than the default
284 interface.
285
286 Example: The following defines a method g, which if called with an
287 argument appends to, rather than overwriting, the current value:
288
289 use Class::MakeMethods::Template::Hash
290 'string' => [ '--get_concat', 'g' ];
291
292 A named interface may also be specified as a default in the argument
293 list with a leading '--' followed by the interface's name.
294
295 Example: Instead of the normal Hash scalar methods (named x and
296 clear_x), the following creates methods with "Java-style" names and
297 behaviors (getx, setx).
298
299 use Class::MakeMethods::Template::Hash
300 'scalar' => [ '--java', 'x' ];
301
302 An interface set in this way affects all meta-methods that follow it
303 until another interface is selected or the end of the array is reached;
304 to return to the original names request the 'default' interface.
305
306 Example: The below creates "Java-style" methods for e and f, "normal
307 scalar" methods for g, and "Eiffel-style" methods for h.
308
309 use Class::MakeMethods::Template::Hash
310 'scalar' => [
311 '--java'=> 'e', 'f',
312 '--default'=> 'g',
313 '--eiffel'=> 'h',
314 ];
315
316 Selecting Modifiers
317 You may select modifiers, which will affect all behaviors.
318
319 use Class::MakeMethods::Template::Hash
320 'scalar' => [ 'a', '--protected' => 'b', --private' => 'c' ];
321
322 Method b croaks if it's called from outside of the current package or
323 its subclasses.
324
325 Method c croaks if it's called from outside of the current package.
326
327 See the documentation for each template to learn which modifiers it
328 supports.
329
330 Runtime Parameter Access
331 If the meta-method is defined using an interface which includes the
332 attributes method, run-time access to meta-method parameters is
333 available.
334
335 Example: The following defines a counter meta-method named y, and then
336 later changes the 'join' parameter for that method at runtime.
337
338 use Class::MakeMethods ( get_concat => 'y' );
339
340 y_attributes(undef, 'join', "\t" )
341 print y_attributes(undef, 'join')
342
344 You can create your own method-generator templates by following the
345 below outline.
346
347 Mechanisms
348 Dynamic generation of methods in Perl generally depends on one of two
349 approaches: string evals, which can be as flexible as your string-
350 manipulation functions allow, but are run-time resource intensive; or
351 closures, which are limited by the number of subroutine constructors
352 you write ahead of time but which are faster and smaller than evals.
353
354 Class::MakeMethods::Template uses both of these approaches: To generate
355 different types of subroutines, a simple text-substitution mechanism
356 combines bits of Perl to produce the source code for a subroutine, and
357 then evals those to produce code refs. Any differences which can be
358 handled with only data changes are managed at the closure layer; once
359 the subroutines are built, they are repeatedly bound as closures to
360 hashes of parameter data.
361
362 Code Generation
363 A substitution-based "macro language" is used to assemble code strings.
364 This happens only once per specific subclass/template/behavior
365 combination used in your program. (If you have disk-caching enabled,
366 the template interpretation is only done once, and then saved; see
367 below.)
368
369 There are numerous examples of this within the Generic interface and
370 its subclasses; for examples, look at the following methods:
371 Universal:generic, Generic:scalar, Hash:generic, and Hash:scalar.
372
373 See Class::MakeMethods::Template::TextBuilder for more information.
374
375 Template Definitions
376 Template method generators are declared by creating a subroutine that
377 returns a hash-ref of information about the template. When these
378 subroutines are first called, the template information is filled in
379 with imported and derived values, blessed as a
380 Class::MakeMethods::Template object, and cached.
381
382 Each "use" of your subclass, or call to its "make", causes these
383 objects to assemble the requested methods and return them to
384 Class::MakeMethods for installation in the calling package.
385
386 Method generators defined this way will have support for parameters,
387 custom interfaces, and the other features discussed above.
388
389 (Your module may also use the "Aliasing" and "Rewriting" functionality
390 described in "EXTENDING" in Class::MakeMethods.)
391
392 Definition hashes contain several types of named resources in a second
393 level of hash-refs under the following keys:
394
395 · interface - Naming styles (see "Defining Interfaces", below)
396
397 · params - Default parameters for meta-methods declared with this
398 template (see "Default Parameters", below)
399
400 · behavior - Method recipes (see "Defining Behaviors", below)
401
402 · code_expr - Bits of code used by the behaviors
403
404 Minimum Template Definition
405 You must at least specify one behavior; all other information is
406 optional.
407
408 Class::MakeMethods will automatically fill in the template name and
409 class as 'template_name' and 'template_class' entries in the version of
410 your template definition hash that it caches and uses for future
411 execution.
412
413 For example a simple sub-class that defines a method type
414 upper_case_get_set might look like this:
415
416 package Class::MakeMethods::UpperCase;
417 use Class::MakeMethods '-isasubclass';
418
419 sub uc_scalar {
420 return {
421 'behavior' => {
422 'default' => sub {
423 my $m_info = $_[0];
424 return sub {
425 my $self = shift;
426 if ( scalar @_ ) {
427 $self->{ $m_info->{'name'} } = uc( shift )
428 } else {
429 $self->{ $m_info->{'name'} };
430 }
431 }
432 },
433 }
434 }
435 }
436
437 And a caller could then use it to generate methods in their package by
438 invoking:
439
440 Class::MakeMethods::UpperCase->make( 'uc_scalar' => [ 'foo' ] );
441
442 Default Parameters
443 Each template may include a set of default parameters for all
444 declarations as "params => hash_ref".
445
446 Template-default parameters can be overrridden by interface '-params',
447 described below, and and method-specific parameters, described above.
448
449 Defining Interfaces
450 Template definitions may have one or more interfaces, including the
451 default one, named 'default', which is automatically selected if
452 another interface is not requested. (If no default interface is
453 provided, one is constructed, which simply calls for a behavior named
454 default.)
455
456 Most commonly, an interface is specified as a hash which maps one or
457 more subroutine names to the behavior to use for each. The interface
458 subroutine names generally contain an asterisk character, '*', which
459 will be replaced by the name of each meta-method.
460
461 Example: The below defines methods e_get, e_set, and e_clear.
462
463 use Class::MakeMethods::Template::Hash
464 'scalar' => [
465 -interface=>{ '*_clear'=>clear, '*_get'=>'get', '*_set'=>'set' }, 'e'
466 ];
467
468 If the provided name does not contain an asterisk, it will not be
469 modified for individual meta-methods; for examples, see the bit_fields
470 method generated by Generic bits, and the DESTROY method generated by
471 InsideOut meta-methods.
472
473 In addition to the name-to-behavior correspondences described above,
474 interfaces may also contain additional entries with keys begining with
475 the '-' character which are interpreted as follows:
476
477 · "-params => hash_ref"
478
479 Interfaces may include a '-params' key and associated reference to
480 a hash of default parameters for that interface.
481
482 · "-base => interface_name"
483
484 Interfaces can be based on previously existing ones by including a
485 -base specification in the the hash. The base value should contain
486 one or more space-separated names of the interfaces to be included.
487
488 Example: The below defines methods getG, setG, and clearG.
489
490 use Class::MakeMethods::Template::Hash
491 'scalar' => [
492 -interface => { -base=>'java', 'clear*'=>'clear' }, qw/ G /
493 ];
494
495 If multiple interfaces are included in the -base specification and
496 specify different behaviors for the same subroutine name, the later
497 ones will override the earlier. Names which appear in the base
498 interface can be overridden by providing a new value, or a name can
499 be removed by mapping it to undef or the empty string.
500
501 Example: The following defines a get-set meta-method h, but
502 supresses the clear_h method:
503
504 use Class::MakeMethods::Template::Hash
505 'scalar' => [
506 -interface => { -base=>'with_clear', 'clear_*'=>'' }, qw/ h /
507 ];
508
509 Defining Behaviors
510 Behaviors can be provided as text which is eval'd to form a closure-
511 generating subroutine when it's first used; $self is automatically
512 defined and assigned the value of the first argument.
513
514 'behavior' => {
515 'default' => q{
516 if ( scalar @_ ) { $self->{ $m_info->{'name'} } = uc shift }
517 $self->{ $m_info->{'name'} };
518 },
519 }
520
521 A simple substitution syntax provides for macro interpretation with
522 definition strings. This functionality is currently undocumented; for
523 additional details see the _interpret_text_builder function in
524 Class::MakeMethods, and review the code_expr hashes defined in
525 Class::MakeMethods::Generic.
526
527 Importing
528 You can copy values out of other template definitions by specifying an
529 '-import' key and corresponding hash reference. You can specify an
530 -import for inside any of the template definition sub-hashes. If no
531 -import is specified for a subhash, and there is a top-level -import
532 value, it is used instead.
533
534 Inside an -import hash, provide "TemplateClass:type" names for each
535 source you wish to copy from, and the values to import, which can be a
536 string, a reference to an array of strings, or '*' to import everything
537 available. (The order of copying is not defined.)
538
539 Example: The below definition creates a new template which is identical
540 to an existing one.
541
542 package Class::MakeMethods::MyMethods;
543 sub scalarama {
544 { -import => { 'Template::Hash:scalar' => '*' } }
545 }
546
547 Values that are already set are not modified, unless they're an array
548 ref, in which case they're added to.
549
550 Example:
551
552 package Class::MakeMethods::MyMethods;
553 sub foo_method {
554 { 'behavior' => {
555 '-init' => [ sub { warn "Defining foo_method $_[0]->{'name'}" } ],
556 'default' => q{ warn "Calling foo_method behavior" }.
557 } }
558 }
559 sub bar_method {
560 { 'behavior' => {
561 -import => { 'MyMethods:foo_method' => '*' },
562 '-init' => [ sub { warn "Defining bar_method $_[0]->{'name'}" } ],
563 'default' => q{ warn "Calling bar_method behavior" }.
564 } }
565 }
566
567 In this case, the bar_method ends up with an array of two '-init'
568 subroutines, its own and the imported one, but only its own default
569 behavior.
570
571 Modifying Existing Templates
572 You can over-write information contained in template definitions to
573 alter their subsequent behavior.
574
575 Example: The following extends the Hash:scalar template definition by
576 adding a new interface, and then uses it to create scalar accessor
577 methods named access_p and access_q that get and set values for the
578 hash keys 'p' and 'q':
579
580 Class::MakeMethods::Template::Hash->named_method('scalar')->
581 {'interface'}{'frozzle'} = { 'access_*'=>'get_set' };
582
583 package My::Object;
584 Class::MakeMethods::Template::Hash->make( 'scalar' => [ --frozzle => qw( p q ) ] );
585
586 $object->access_p('Potato'); # $object->{p} = 'Potato'
587 print $object->access_q(); # print $object->{q}
588
589 Note that this constitutes "action at a distance" and will affect
590 subsequent use by other packages; unless you are "fixing" the current
591 behavior, you are urged to create your own template definition which
592 imports the base behavior of the existing template and overrides the
593 information in question.
594
595 Example: The following safely declares a new version of Hash:scalar
596 with the desired additional interface:
597
598 package My::Methods;
599
600 sub scalar {
601 {
602 -import => { 'Template::Hash:scalar' => '*' } ,
603 interface => { 'frozzle' => { 'access_*'=>'get_set' } },
604 }
605 }
606
607 package My::Object;
608 My::Methods->make( 'scalar' => [ --frozzle => qw( p q ) ] );
609
610 Disk Caching
611 To enable disk caching of generated code, create an empty directory and
612 pass it to the DiskCache package:
613
614 use Class::MakeMethods::Template::DiskCache qw( /my/code/dir );
615
616 This has a mixed effect on performance, but has the notable advantage
617 of letting you view the subroutines that are being generated by your
618 templates.
619
620 See Class::MakeMethods::Template::DiskCache for more information.
621
623 See Class::MakeMethods for general information about this distribution.
624
625 See Class::MakeMethods::Examples for some illustrations of what you can
626 do with this package.
627
628
629
630perl v5.32.0 2020-07-28 MakeMethods::Template(3)