1MakeMethods(3) User Contributed Perl Documentation MakeMethods(3)
2
3
4
6 Class::MakeMethods - Generate common types of methods
7
9 # Generates methods for your object when you "use" it.
10 package MyObject;
11 use Class::MakeMethods::Standard::Hash (
12 'new' => 'new',
13 'scalar' => 'foo',
14 'scalar' => 'bar',
15 );
16
17 # The generated methods can be called just like normal ones
18 my $obj = MyObject->new( foo => "Foozle", bar => "Bozzle" );
19 print $obj->foo();
20 $obj->bar("Barbados");
21
23 The Class::MakeMethods framework allows Perl class developers to
24 quickly define common types of methods. When a module "use"s
25 Class::MakeMethods or one of its subclasses, it can select from a
26 variety of supported method types, and specify a name for each method
27 desired. The methods are dynamically generated and installed in the
28 calling package.
29
30 Construction of the individual methods is handled by subclasses. This
31 delegation approach allows for a wide variety of method-generation
32 techniques to be supported, each by a different subclass. Subclasses
33 can also be added to provide support for new types of methods.
34
35 Over a dozen subclasses are available, including implementations of a
36 variety of different method-generation techniques. Each subclass
37 generates several types of methods, with some supporting their own
38 open-eneded extension syntax, for hundreds of possible combinations of
39 method types.
40
42 Motivation
43 "Make easy things easier."
44
45 This module addresses a problem encountered in object-oriented
46 development wherein numerous methods are defined which differ only
47 slightly from each other.
48
49 A common example is accessor methods for hash-based object attributes,
50 which allow you to get and set the value $self->{'foo'} by calling a
51 method $self->foo().
52
53 These methods are generally quite simple, requiring only a couple of
54 lines of Perl, but in sufficient bulk, they can cut down on the
55 maintainability of large classes.
56
57 Class::MakeMethods allows you to simply declare those methods to be of
58 a predefined type, and it generates and installs the necessary methods
59 in your package at compile-time.
60
61 A Contrived Example
62 Object-oriented Perl code is widespread -- you've probably seen code
63 like the below a million times:
64
65 my $obj = MyStruct->new( foo=>"Foozle", bar=>"Bozzle" );
66 if ( $obj->foo() =~ /foo/i ) {
67 $obj->bar("Barbados!");
68 }
69 print $obj->summary();
70
71 (If this doesn't look familiar, take a moment to read perlboot and
72 you'll soon learn more than's good for you.)
73
74 Typically, this involves creating numerous subroutines that follow a
75 handful of common patterns, like constructor methods and accessor
76 methods. The classic example is accessor methods for hash-based object
77 attributes, which allow you to get and set the value self->{foo} by
78 calling a method self->foo(). These methods are generally quite
79 simple, requiring only a couple of lines of Perl, but in sufficient
80 bulk, they can cut down on the maintainability of large classes.
81
82 Here's a possible implementation for the class whose interface is shown
83 above:
84
85 package MyStruct;
86
87 sub new {
88 my $callee = shift;
89 my $self = bless { @_ }, (ref $callee || $callee);
90 return $self;
91 }
92
93 sub foo {
94 my $self = shift;
95 if ( scalar @_ ) {
96 $self->{'foo'} = shift();
97 } else {
98 $self->{'foo'}
99 }
100 }
101
102 sub bar {
103 my $self = shift;
104 if ( scalar @_ ) {
105 $self->{'bar'} = shift();
106 } else {
107 $self->{'bar'}
108 }
109 }
110
111 sub summary {
112 my $self = shift;
113 join(', ', map { "\u$_: " . $self->$_() } qw( foo bar ) )
114 }
115
116 Note in particular that the foo and bar methods are almost identical,
117 and that the new method could be used for almost any class; this is
118 precisely the type of redundancy Class::MakeMethods addresses.
119
120 Class::MakeMethods allows you to simply declare those methods to be of
121 a predefined type, and it generates and installs the necessary methods
122 in your package at compile-time.
123
124 Here's the equivalent declaration for that same basic class:
125
126 package MyStruct;
127 use Class::MakeMethods::Standard::Hash (
128 'new' => 'new',
129 'scalar' => 'foo',
130 'scalar' => 'bar',
131 );
132
133 sub summary {
134 my $self = shift;
135 join(', ', map { "\u$_: " . $self->$_() } qw( foo bar ) )
136 }
137
138 This is the basic purpose of Class::MakeMethods: The "boring" pieces of
139 code have been replaced by succinct declarations, placing the focus on
140 the "unique" or "custom" pieces.
141
142 Finding the Method Types You Need
143 Once you've grasped the basic idea -- simplifying repetitive code by
144 generating and installing methods on demand -- the remaining complexity
145 basically boils down to figuring out which arguments to pass to
146 generate the specific methods you want.
147
148 Unfortunately, this is not a trivial task, as there are dozens of
149 different types of methods that can be generated, each with a variety
150 of options, and several alternative ways to write each method
151 declaration. You may prefer to start by just finding a few examples
152 that you can modify to accomplish your immediate needs, and defer
153 investigating all of the extras until you're ready to take a closer
154 look.
155
156 Other Documentation
157 The remainder of this document focuses on points of usage that are
158 common across all subclasses, and describes how to create your own
159 subclasses.
160
161 If this is your first exposure to Class::MakeMethods, you may want to
162 skim over the rest of this document, then take a look at the examples
163 and one or two of the method-generating subclasses to get a more
164 concrete sense of typical usage, before returning to the details
165 presented below.
166
167 · A collection of sample uses is available in
168 Class::MakeMethods::Docs::Examples.
169
170 · Some of the most common object and class methods are available from
171 Class::MakeMethods::Standard::Hash,
172 Class::MakeMethods::Standard::Global and
173 Class::MakeMethods::Standard::Universal.
174
175 · If you need a bit more flexibility, see
176 Class::MakeMethods::Composite for method generators which offer
177 more customization options, including pre- and post-method callback
178 hooks.
179
180 · For the largest collection of methods and options, see
181 Class::MakeMethods::Template, which uses a system of dynamic code
182 generation to allow endless variation.
183
184 · A listing of available method types from each of the different
185 subclasses is provided in Class::MakeMethods::Docs::Catalog.
186
188 Because there are so many common types of methods one might wish to
189 generate, the Class::MakeMethods framework provides an extensible
190 system based on subclasses.
191
192 When your code requests a method, the MakeMethods base class performs
193 some standard argument parsing, delegates the construction of the
194 actual method to the appropriate subclass, and then installs whatever
195 method the subclass returns.
196
197 The MakeMethods Base Class
198 The Class::MakeMethods package defines a superclass for method-
199 generating modules, and provides a calling convention, on-the-fly
200 subclass loading, and subroutine installation that will be shared by
201 all subclasses.
202
203 The superclass also lets you generate several different types of
204 methods in a single call, and will automatically load named subclasses
205 the first time they're used.
206
207 The Method Generator Subclasses
208 The type of method that gets created is controlled by the specific
209 subclass and generator function you request. For example,
210 "Class::MakeMethods::Standard::Hash" has a generator function
211 "scalar()", which is responsible for generating simple scalar-accessor
212 methods for blessed-hash objects.
213
214 Each generator function specified is passed the arguments specifying
215 the method the caller wants, and produces a closure or eval-able
216 sequence of Perl statements representing the ready-to-install function.
217
218 Included Subclasses
219 Because each subclass defines its own set of method types and
220 customization options, a key step is to find your way to the
221 appropriate subclasses.
222
223 Standard (See Class::MakeMethods::Standard.)
224 Generally you will want to begin with the Standard::Hash subclass,
225 to create constructor and accessor methods for working with
226 blessed-hash objects (or you might choose the Standard::Array
227 subclass instead). The Standard::Global subclass provides methods
228 for class data shared by all objects in a class.
229
230 Each Standard method declaration can optionally include a hash of
231 associated parameters, which allows you to tweak some of the
232 characteristics of the methods. Subroutines are bound as closures
233 to a hash of each method's name and parameters. Standard::Hash and
234 Standard::Array provide object constructor and accessors. The
235 Standard::Global provides for static data shared by all instances
236 and subclasses, while the data for Standard::Inheritable methods
237 trace the inheritance tree to find values, and can be overriden for
238 any subclass or instance.
239
240 Composite (See Class::MakeMethods::Composite.)
241 For additional customization options, check out the Composite
242 subclasses, which allow you to select from a more varied set of
243 implementations and which allow you to adjust any specific method
244 by adding your own code-refs to be run before or after it.
245
246 Subroutines are bound as closures to a hash of each method's name
247 and optional additional data, and to one or more subroutine
248 references which make up the composite behavior of the method.
249 Composite::Hash and Composite::Array provide object constructor and
250 accessors. The Composite::Global provides for static data shared by
251 all instances and subclasses, while the data for
252 Composite::Inheritable methods can be overriden for any subclass or
253 instance.
254
255 Template (See Class::MakeMethods::Template.)
256 The Template subclasses provide an open-ended structure for objects
257 that assemble Perl code on the fly into cachable closure-generating
258 subroutines; if the method you need isn't included, you can extend
259 existing methods by re-defining just the snippet of code that's
260 different.
261
262 Class::MakeMethods::Template extends MakeMethods with a text
263 templating system that can assemble Perl code fragments into a
264 desired subroutine. The code for generated methods is eval'd once
265 for each type, and then repeatedly bound as closures to method-
266 specific data for better performance.
267
268 Templates for dozens of types of constructor, accessor, and mutator
269 methods are included, ranging from from the mundane (constructors
270 and value accessors for hash and array slots) to the esoteric
271 (inheritable class data and "inside-out" accessors with external
272 indexes).
273
274 Basic (See Class::MakeMethods::Basic.)
275 The Basic subclasses provide stripped down method generators with
276 no configurable options, for minimal functionality (and minimum
277 overhead).
278
279 Subroutines are bound as closures to the name of each method.
280 Basic::Hash and Basic::Array provide simple object constructors and
281 accessors. Basic::Global provides basic global-data accessors.
282
283 Emulators (See Class::MakeMethods::Emulator.)
284 In several cases, Class::MakeMethods provides functionality closely
285 equivalent to that of an existing module, and it is simple to map
286 the existing module's interface to that of Class::MakeMethods.
287
288 Emulators are included for Class::MethodMaker,
289 Class::Accessor::Fast, Class::Data::Inheritable, Class::Singleton,
290 and Class::Struct, each of which passes the original module's test
291 suite, usually requiring only that the name of the module be
292 changed.
293
294 Extending
295 Class::MakeMethods can be extended by creating subclasses that
296 define additional method-generation functions. Callers can then
297 specify the name of your subclass and generator function in their
298 "use Call::MakeMethods ..." statements and your function will be
299 invoked to produce the required closures. See "EXTENDING" for more
300 information.
301
302 Naming Convention for Generated Method Types
303 Method generation functions in this document are often referred to
304 using the 'MakerClass:MethodType' or
305 'MakerGroup::MakerSubclass:MethodType' naming conventions. As you will
306 see, these are simply the names of Perl packages and the names of
307 functions that are contained in those packages.
308
309 The included subclasses are grouped into several major groups, so the
310 names used by the included subclasses and method types reflect three
311 axes of variation, "Group::Subclass:Type":
312
313 Maker Group
314 Each group shares a similar style of technical implementation and
315 level of complexity. For example, the "Standard::*" packages are
316 all simple, while the "Composite::*" packages all support pre- and
317 post-conditions.
318
319 (For a listing of the four main groups of included subclasses, see
320 "Included Subclasses"" in ".)
321
322 Maker Subclass
323 Each subclass generates methods for a similar level of scoping or
324 underlying object type. For example, the *::Hash packages all make
325 methods for objects based on blessed hashes, while the *::Global
326 packages make methods that access class-wide data that will be
327 shared between all objects in a class.
328
329 Method Type
330 Each method type produces a similar type of constructor or
331 accessor. For examples, the *:new methods are all constructors,
332 while the "::scalar" methods are all accessors that allow you to
333 get and set a single scalar value.
334
335 Bearing that in mind, you should be able to guess the intent of many of
336 the method types based on their names alone; when you see
337 "Standard::Hash:scalar" you can read it as "a type of method to access
338 a scalar value stored in a hash-based object, with a standard
339 implementation style" and know that it's going to call the scalar()
340 function in the Class::MakeMethods::Standard::Hash package to generate
341 the requested method.
342
344 The supported method types, and the kinds of arguments they expect,
345 vary from subclass to subclass; see the documentation of each subclass
346 for details.
347
348 However, the features described below are applicable to all subclasses.
349
350 Invocation
351 Methods are dynamically generated and installed into the calling
352 package when you "use Class::MakeMethods (...)" or one of its
353 subclasses, or if you later call "Class::MakeMethods->make(...)".
354
355 The arguments to "use" or "make" should be pairs of a generator type
356 name and an associated array of method-name arguments to pass to the
357 generator.
358
359 · use Class::MakeMethods::MakerClass (
360 'MethodType' => [ Arguments ], ...
361 );
362
363 · Class::MakeMethods::MakerClass->make (
364 'MethodType' => [ Arguments ], ...
365 );
366
367 You may select a specific subclass of Class::MakeMethods for a single
368 generator-type/argument pair by prefixing the type name with a subclass
369 name and a colon.
370
371 · use Class::MakeMethods (
372 'MakerClass:MethodType' => [ Arguments ], ...
373 );
374
375 · Class::MakeMethods->make (
376 'MakerClass:MethodType' => [ Arguments ], ...
377 );
378
379 The difference between "use" and "make" is primarily one of precedence;
380 the "use" keyword acts as a BEGIN block, and is thus evaluated before
381 "make" would be. (See "About Precedence" for additional discussion of
382 this issue.)
383
384 Alternative Invocation
385 If you want methods to be declared at run-time when a previously-
386 unknown method is invoked, see Class::MakeMethods::Autoload.
387
388 · use Class::MakeMethods::Autoload 'MakerClass:MethodType';
389
390 If you are using Perl version 5.6 or later, see
391 Class::MakeMethods::Attribute for an additional declaration syntax for
392 generated methods.
393
394 · use Class::MakeMethods::Attribute 'MakerClass';
395
396 sub name :MakeMethod('MethodType' => Arguments);
397
398 Mixing Method Types
399 A single calling class can combine generated methods from different
400 MakeMethods subclasses. In general, the only mixing that's problematic
401 is combinations of methods which depend on different underlying object
402 types, like using *::Hash and *::Array methods together -- the methods
403 will be generated, but some of them are guaranteed to fail when
404 called, depending on whether your object happens to be a blessed
405 hashref or arrayref.
406
407 For example, it's common to mix and match various *::Hash methods, with
408 a scattering of Global or Inheritable methods:
409
410 use Class::MakeMethods (
411 'Basic::Hash:scalar' => 'foo',
412 'Composite::Hash:scalar' => [ 'bar' => { post_rules => [] } ],
413 'Standard::Global:scalar' => 'our_shared_baz'
414 );
415
416 Argument Normalization
417 The following expansion rules are applied to argument pairs to enable
418 the use of simple strings instead of arrays of arguments.
419
420 · Each type can be followed by a single meta-method definition, or by
421 a reference to an array of them.
422
423 · If the argument is provided as a string containing spaces, it is
424 split and each word is treated as a separate argument.
425
426 · It the meta-method type string contains spaces, it is split and
427 only the first word is used as the type, while the remaining words
428 are placed at the front of the argument list.
429
430 For example, the following statements are equivalent ways of declaring
431 a pair of Basic::Hash scalar methods named 'foo' and 'bar':
432
433 use Class::MakeMethods::Basic::Hash (
434 'scalar' => [ 'foo', 'bar' ],
435 );
436
437 use Class::MakeMethods::Basic::Hash (
438 'scalar' => 'foo',
439 'scalar' => 'bar',
440 );
441
442 use Class::MakeMethods::Basic::Hash (
443 'scalar' => 'foo bar',
444 );
445
446 use Class::MakeMethods::Basic::Hash (
447 'scalar foo' => 'bar',
448 );
449
450 (The last of these is clearly a bit peculiar and potentially misleading
451 if used as shown, but it enables advanced subclasses to provide
452 convenient formatting for declarations with defaults or modifiers,
453 such as 'Template::Hash:scalar --private' => 'foo', discussed
454 elsewhere.)
455
456 Global Parameters
457 Global parameters may be specified as an argument pair with a leading
458 hyphen. (This distinguishes them from type names, which must be valid
459 Perl subroutine names, and thus will never begin with a hyphen.)
460
461 use Class::MakeMethods::MakerClass (
462 '-Param' => ParamValue,
463 'MethodType' => [ Arguments ], ...
464 );
465
466 Parameter settings apply to all subsequent method declarations within a
467 single "use" or "make" call.
468
469 The below parameters allow you to control generation and installation
470 of the requested methods. (Some subclasses may support additional
471 parameters; see their documentation for details.)
472
473 -TargetClass
474 By default, the methods are installed in the first package in the
475 caller() stack that is not a Class::MakeMethods subclass; this is
476 generally the package in which your use or make statement was
477 issued. To override this you can pass "-TargetClass => package" as
478 initial arguments to "use" or "make".
479
480 This allows you to construct or modify classes "from the outside":
481
482 package main;
483
484 use Class::MakeMethods::Basic::Hash(
485 -TargetClass => 'MyWidget',
486 'new' => ['create'],
487 'scalar' => ['foo', 'bar'],
488 );
489
490 $o = MyWidget->new( foo => 'Foozle' );
491 print $o->foo();
492
493 -MakerClass
494 By default, meta-methods are looked up in the package you called
495 use or make on.
496
497 You can override this by passing the "-MakerClass" flag, which
498 allows you to switch packages for the remainder of the meta-method
499 types and arguments.
500
501 use Class::MakeMethods (
502 '-MakerClass'=>'MakerClass',
503 'MethodType' => [ Arguments ]
504 );
505
506 When specifying the MakerClass, you may provide either the trailing
507 part name of a subclass inside of the "Class::MakeMethods::"
508 namespace, or a full package name prefixed by "::".
509
510 For example, the following four statements are equivalent ways of
511 declaring a Basic::Hash scalar method named 'foo':
512
513 use Class::MakeMethods::Basic::Hash (
514 'scalar' => [ 'foo' ]
515 );
516
517 use Class::MakeMethods (
518 'Basic::Hash:scalar' => [ 'foo' ]
519 );
520
521 use Class::MakeMethods (
522 '-MakerClass'=>'Basic::Hash',
523 'scalar' => [ 'foo' ]
524 );
525
526 use Class::MakeMethods (
527 '-MakerClass'=>'::Class::MakeMethods::Basic::Hash',
528 'scalar' => [ 'foo' ]
529 );
530
531 -ForceInstall
532 By default, Class::MakeMethods will not install generated methods
533 over any pre-existing methods in the target class. To override this
534 you can pass "-ForceInstall => 1" as initial arguments to "use" or
535 "make".
536
537 Note that the "use" keyword acts as a BEGIN block, so a "use" at
538 the top of a file will be executed before any subroutine
539 declarations later in the file have been seen. (See "About
540 Precedence" for additional discussion of this issue.)
541
542 About Precedence
543 Rather than passing the method declaration arguments when you "use" one
544 of these packages, you may instead pass them to a subsequent call to
545 the class method "make".
546
547 The difference between "use" and "make" is primarily one of precedence;
548 the "use" keyword acts as a BEGIN block, and is thus evaluated before
549 "make" would be. In particular, a "use" at the top of a file will be
550 executed before any subroutine declarations later in the file have been
551 seen, whereas a "make" at the same point in the file will not.
552
553 By default, Class::MakeMethods will not install generated methods over
554 any pre-existing methods in the target class. To override this you can
555 pass "-ForceInstall => 1" as initial arguments to "use" or "make".
556
557 If the same method is declared multiple times, earlier calls to "use"
558 or "make()" win over later ones, but within each call, later
559 declarations superceed earlier ones.
560
561 Here are some examples of the results of these precedence rules:
562
563 # 1 - use, before
564 use Class::MakeMethods::Standard::Hash (
565 'scalar'=>['baz'] # baz() not seen yet, so we generate, install
566 );
567 sub baz { 1 } # Subsequent declaration overwrites it, with warning
568
569 # 2 - use, after
570 sub foo { 1 }
571 use Class::MakeMethods::Standard::Hash (
572 'scalar'=>['foo'] # foo() is already declared, so has no effect
573 );
574
575 # 3 - use, after, Force
576 sub bar { 1 }
577 use Class::MakeMethods::Standard::Hash (
578 -ForceInstall => 1, # Set flag for following methods...
579 'scalar' => ['bar'] # ... now overwrites pre-existing bar()
580 );
581
582 # 4 - make, before
583 Class::MakeMethods::Standard::Hash->make(
584 'scalar'=>['blip'] # blip() is already declared, so has no effect
585 );
586 sub blip { 1 } # Although lower than make(), this "happens" first
587
588 # 5 - make, after, Force
589 sub ping { 1 }
590 Class::MakeMethods::Standard::Hash->make(
591 -ForceInstall => 1, # Set flag for following methods...
592 'scalar' => ['ping'] # ... now overwrites pre-existing ping()
593 );
594
595 Diagnostic Messages
596 The following warnings and errors may be produced when using
597 Class::MakeMethods to generate methods. (Note that this list does not
598 include run-time messages produced by calling the generated methods.)
599
600 These messages are classified as follows (listed in increasing order of
601 desperation):
602
603 (Q) A debugging message, only shown if $CONTEXT{Debug} is true
604 (W) A warning.
605 (D) A deprecation.
606 (F) A fatal error in caller's use of the module.
607 (I) An internal problem with the module or subclasses.
608
609 Portions of the message which may vary are denoted with a %s.
610
611 Can't interpret meta-method template: argument is empty or undefined
612 (F)
613
614 Can't interpret meta-method template: unknown template name '%s'
615 (F)
616
617 Can't interpret meta-method template: unsupported template type '%s'
618 (F)
619
620 Can't make method %s(): template specifies unknown behavior '%s'
621 (F)
622
623 Can't parse meta-method declaration: argument is empty or undefined
624 (F) You passed an undefined value or an empty string in the list of
625 meta-method declarations to use or make.
626
627 Can't parse meta-method declaration: missing name attribute.
628 (F) You included an hash-ref-style meta-method declaration that did
629 not include the required name attribute. You may have meant this to
630 be an attributes hash for a previously specified name, but if so we
631 were unable to locate it.
632
633 Can't parse meta-method declaration: unknown template name '%s'
634 (F) You included a template specifier of the form '-template_name'
635 in a the list of meta-method declaration, but that template is not
636 available.
637
638 Can't parse meta-method declaration: unsupported declaration type '%s'
639 (F) You included an unsupported type of value in a list of meta-
640 method declarations.
641
642 Compilation error: %s
643 (I)
644
645 Not an interpretable meta-method: '%s'
646 (I)
647
648 Odd number of arguments passed to %s make
649 (F) You specified an odd number of arguments in a call to use or
650 make. The arguments should be key => value pairs.
651
652 Unable to compile generated method %s(): %s
653 (I) The install_methods subroutine attempted to compile a
654 subroutine by calling eval on a provided string, which failed for
655 the indicated reason, usually some type of Perl syntax error.
656
657 Unable to dynamically load $package: $%s
658 (F)
659
660 Unable to install code for %s() method: '%s'
661 (I) The install_methods subroutine was passed an unsupported value
662 as the code to install for the named method.
663
664 Unexpected return value from compilation of %s(): '%s'
665 (I) The install_methods subroutine attempted to compile a
666 subroutine by calling eval on a provided string, but the eval
667 returned something other than than the code ref we expect.
668
669 Unexpected return value from meta-method constructor %s: %s
670 (I) The requested method-generator was invoked, but it returned an
671 unacceptable value.
672
674 Class::MakeMethods can be extended by creating subclasses that define
675 additional meta-method types. Callers then select your subclass using
676 any of the several techniques described above.
677
678 Creating A Subclass
679 The begining of a typical extension might look like the below:
680
681 package My::UpperCaseMethods;
682 use strict;
683 use Class::MakeMethods '-isasubclass';
684
685 sub my_method_type { ... }
686
687 You can name your subclass anything you want; it does not need to begin
688 with Class::MakeMethods.
689
690 The '-isasubclass' flag is a shortcut that automatically puts
691 Class::MakeMethods into your package's @ISA array so that it will
692 inherit the import() and make() class methods. If you omit this flag,
693 you will need to place the superclass in your @ISA explicitly.
694
695 Typically, the subclass should not inherit from Exporter; both
696 Class::MakeMethods and Exporter are based on inheriting an import class
697 method, and getting a subclass to support both would require additional
698 effort.
699
700 Naming Method Types
701 Each type of method that can be generated is defined in a subroutine of
702 the same name. You can give your meta-method type any name that is a
703 legal subroutine identifier.
704
705 (Names begining with an underscore, and the names "import" and "make",
706 are reserved for internal use by Class::MakeMethods.)
707
708 If you plan on distributing your extension, you may wish to follow the
709 "Naming Convention for Generated Method Types" described above to
710 facilitate reuse by others.
711
712 Implementation Options
713 Each method generation subroutine can be implemented in any one of the
714 following ways:
715
716 · Subroutine Generation
717
718 Returns a list of subroutine name/code pairs.
719
720 The code returned may either be a coderef, or a string containing
721 Perl code that can be evaled and will return a coderef. If the eval
722 fails, or anything other than a coderef is returned, then
723 Class::MakeMethods croaks.
724
725 For example a simple sub-class with a method type
726 upper_case_get_set that generates an accessor method for each
727 argument provided might look like this:
728
729 package My::UpperCaseMethods;
730 use Class::MakeMethods '-isasubclass';
731
732 sub uc_scalar {
733 my $class = shift;
734 map {
735 my $name = $_;
736 $name => sub {
737 my $self = shift;
738 if ( scalar @_ ) {
739 $self->{ $name } = uc( shift )
740 } else {
741 $self->{ $name };
742 }
743 }
744 } @_;
745 }
746
747 Callers could then generate these methods as follows:
748
749 use My::UpperCaseMethods ( 'uc_scalar' => 'foo' );
750
751 · Aliasing
752
753 Returns a string containing a different meta-method type to use for
754 those same arguments.
755
756 For example a simple sub-class that defines a method type
757 stored_value might look like this:
758
759 package My::UpperCaseMethods;
760 use Class::MakeMethods '-isasubclass';
761
762 sub regular_scalar { return 'Basic::Hash:scalar' }
763
764 And here's an example usage:
765
766 use My::UpperCaseMethods ( 'regular_scalar' => [ 'foo' ] );
767
768 · Rewriting
769
770 Returns one or more array references with different meta-method
771 types and arguments to use.
772
773 For example, the below meta-method definition reviews the name of
774 each method it's passed and creates different types of meta-methods
775 based on whether the declared name is in all upper case:
776
777 package My::UpperCaseMethods;
778 use Class::MakeMethods '-isasubclass';
779
780 sub auto_detect {
781 my $class = shift;
782 my @rewrite = ( [ 'Basic::Hash:scalar' ],
783 [ '::My::UpperCaseMethods:uc_scalar' ] );
784 foreach ( @_ ) {
785 my $name_is_uppercase = ( $_ eq uc($_) ) ? 1 : 0;
786 push @{ $rewrite[ $name_is_uppercase ] }, $_
787 }
788 return @rewrite;
789 }
790
791 The following invocation would then generate a regular scalar
792 accessor method foo, and a uc_scalar method BAR:
793
794 use My::UpperCaseMethods ( 'auto_detect' => [ 'foo', 'BAR' ] );
795
796 · Generator Object
797
798 Returns an object with a method named make_methods which will be
799 responsible for returning subroutine name/code pairs.
800
801 See Class::MakeMethods::Template for an example.
802
803 · Self-Contained
804
805 Your code may do whatever it wishes, and return an empty list.
806
807 Access to Parameters
808 Global parameter values are available through the _context() class
809 method at the time that method generation is being performed.
810
811 package My::Maker;
812 sub my_methodtype {
813 my $class = shift;
814 warn "Installing in " . $class->_context('TargetClass');
815 ...
816 }
817
818 · TargetClass
819
820 Class into which code should be installed.
821
822 · MakerClass
823
824 Which subclass of Class::MakeMethods will generate the methods?
825
826 · ForceInstall
827
828 Controls whether generated methods will be installed over pre-
829 existing methods in the target package.
830
832 Package Documentation
833 A collection of sample uses is available in
834 Class::MakeMethods::Docs::Examples.
835
836 See the documentation for each family of subclasses:
837
838 · Class::MakeMethods::Basic
839
840 · Class::MakeMethods::Standard
841
842 · Class::MakeMethods::Composite
843
844 · Class::MakeMethods::Template
845
846 A listing of available method types from each of the different
847 subclasses is provided in Class::MakeMethods::Docs::Catalog.
848
849 Related Modules
850 For a brief survey of the numerous modules on CPAN which offer some
851 type of method generation, see
852 Class::MakeMethods::Docs::RelatedModules.
853
854 If you have used Class::MethodMaker, you will note numerous
855 similarities. Class::MakeMethods is based on Class::MethodMaker, but
856 has been substantially revised in order to provide a range of new
857 features. Backward compatibility and conversion documentation is
858 provded in Class::MakeMethods::Emulator::MethodMaker.
859
860 In several cases, Class::MakeMethods provides functionality closely
861 equivalent to that of an existing module, and emulator modules are
862 provided to map the existing module's interface to that of
863 Class::MakeMethods. See Class::MakeMethods::Emulator for more
864 information.
865
866 Perl Docs
867 See perlboot for a quick introduction to objects for beginners. For an
868 extensive discussion of various approaches to class construction, see
869 perltoot and perltootc (called perltootc in the most recent versions of
870 Perl).
871
872 See "Making References" in perlref, point 4 for more information on
873 closures. (FWIW, I think there's a big opportunity for a "perlfunt"
874 podfile bundled with Perl in the tradition of "perlboot" and
875 "perltoot", exploring the utility of function references, callbacks,
876 closures, and continuations... There are a bunch of useful references
877 available, but not a good overview of how they all interact in a
878 Perlish way.)
879
881 Release Status
882 This module has been used in a variety of production systems and has
883 been available on CPAN for over two years, with several other
884 distributions dependant on it, so it would be fair to say that it is
885 fully released.
886
887 However, while some portions are well tested, others are less so, and
888 new bug reports do trickle in occasionally. If you do encounter any
889 problems, please inform the author and I'll endeavor to patch them
890 promptly.
891
892 Additional features have been outlined for future development, but the
893 intent is support these by adding more options to the declaration
894 interface, while maintaining backward compatibility.
895
896 Known Problems
897 It does not appear to be possible to assign subroutine names to
898 closures within Perl. As a result, debugging output from Carp and
899 similar sources will show all generated methods as "ANON()" rather than
900 "YourClass::methodname()".
901
902 See Class::MakeMethods::Docs::ToDo for other outstanding issues and
903 development plans.
904
905 Support
906 If you have questions or feedback about this module, please feel free
907 to contact the author at the below address. Although there is no formal
908 support program, I do attempt to answer email promptly.
909
910 I would be particularly interested in any suggestions towards improving
911 the documentation, correcting any Perl-version or platform
912 dependencies, as well as general feedback and suggested additions.
913
914 Bug reports that contain a failing test case are greatly appreciated,
915 and suggested patches will be promptly considered for inclusion in
916 future releases.
917
918 To report bugs via the CPAN web tracking system, go to
919 "http://rt.cpan.org/NoAuth/Bugs.html?Dist=Class-MakeMethods" or send
920 mail to "Dist=Class-MakeMethods#rt.cpan.org", replacing "#" with "@".
921
922 Community
923 If you've found this module useful or have feedback about your
924 experience with it, consider sharing your opinion with other Perl users
925 by posting your comment to CPAN's ratings system:
926
927 · http://cpanratings.perl.org/rate/?distribution=Class-MakeMethods
928
929 For more general discussion, you may wish to post a message on
930 PerlMonks or the comp.lang.perl.misc newsgroup:
931
932 · http://www.perlmonks.org/index.pl?node=Seekers%20of%20Perl%20Wisdom
933
934 · http://groups.google.com/groups?group=comp.lang.perl.misc
935
937 Version
938 This is Class::MakeMethods v1.009, intended for general use.
939
940 This module's CPAN registration should read:
941
942 Name DSLIP Description
943 -------------- ----- ---------------------------------------------
944 Class::
945 ::MakeMethods RdpOp Generate common types of methods
946
947 Prerequisites
948 In general, this module should work with Perl 5.003 or later, without
949 requring any modules beyond the core Perl distribution.
950
951 The following optional feature may not be available on some platforms:
952
953 · Class::MakeMethods::Attribute: The ":MakeMethod" subroutine
954 attribute requires Perl version 5.6 and the Attribute::Handlers
955 module (from CPAN).
956
957 · Class::MakeMethods::Template "--lvalue": The lvalue modifier
958 provided by the Template generator subclasses will only work on
959 Perl version 5.6 or later.
960
961 Installation
962 You should be able to install this module using the CPAN shell
963 interface:
964
965 perl -MCPAN -e 'install Class::MakeMethods'
966
967 Alternately, you may retrieve this package from CPAN or from the
968 author's site:
969
970 · http://search.cpan.org/~evo/
971
972 · http://www.cpan.org/modules/by-authors/id/E/EV/EVO
973
974 · http://www.evoscript.org/Class-MakeMethods/dist/
975
976 After downloading the distribution, follow the normal procedure to
977 unpack and install it, using the commands shown below or their local
978 equivalents on your system:
979
980 tar xzf Class-MakeMethods-*.tar.gz
981 cd Class-MakeMethods-*
982 perl Makefile.PL
983 make test && sudo make install
984
985 Thanks to the kind generosity of other members of the Perl community,
986 this distribution is also available repackaged in the FreeBSD "ports"
987 and Linux RPM formats. This may simplify installation for some users,
988 but be aware that these alternate distributions may lag a few versions
989 behind the latest release on CPAN.
990
991 · http://www.freebsd.org/cgi/ports.cgi?query=Class-MakeMethods
992
993 · http://www.rpmfind.net/linux/rpm2html/search.php?query=perl-Class-MakeMethods
994
995 Tested Platforms
996 This release has been tested succesfully on the following platforms:
997
998 5.6.1 on darwin
999
1000 Earlier releases have also tested OK on the following platforms:
1001
1002 IP30-R12000-irix
1003 OpenBSD.i386-openbsd
1004 i386-freebsd / i386-freebsd-thread-multi
1005 i386-linux
1006 i386-netbsd / i386-netbsd-thread-multi
1007 i586-linux / i586-linux-thread-multi-ld
1008 i686-linux / i686-pld-linux-thread-multi
1009 ia64-linux
1010 ppc-linux
1011 sparc-linux
1012 sparc-netbsd
1013 sun4-solaris
1014
1015 Some earlier versions failed to "make test" on MSWin32, although a
1016 forced installation would still work; that problem should be fixed in
1017 the most recent releases.
1018
1019 You may also review the current test results from CPAN-Testers:
1020
1021 · http://testers.cpan.org/show/Class-MakeMethods.html
1022
1024 Author
1025 Developed by Matthew Simon Cavalletto at Evolution Softworks. More
1026 free Perl software is available at "www.evoscript.org".
1027
1028 You may contact the author directly at "evo@cpan.org" or
1029 "simonm@cavalletto.org".
1030
1031 Feedback and Suggestions
1032 Thanks to the following people for bug reports, suggestions, and other
1033 feedback:
1034
1035 Martyn J. Pearce
1036 Scott R. Godin
1037 Ron Savage
1038 Jay Lawrence
1039 Adam Spiers
1040 Malcolm Cook
1041 Terrence Brannon
1042 Jared Rhine
1043 Peter Chen
1044 Mike Castle
1045
1046 Source Material
1047 This package was inspired by the ground-breaking original closure-
1048 generating method maker module:
1049
1050 Class::MethodMaker, by Peter Seibel.
1051
1052 Additional inspiration, cool tricks, and blocks of useful code for this
1053 module were extracted from the following CPAN modules:
1054
1055 Class::Accessor, by Michael G Schwern
1056 Class::Contract, by Damian Conway
1057 Class::SelfMethods, by Toby Everett
1058
1059 Copyright
1060 Copyright 2002, 2003 Matthew Simon Cavalletto.
1061
1062 Portions copyright 1998, 1999, 2000, 2001 Evolution Online Systems,
1063 Inc.
1064
1065 Based on Class::MethodMaker, originally developed by Peter Seibel.
1066 Portions Copyright 1996 Organic Online. Portions Copyright 2000 Martyn
1067 J. Pearce.
1068
1069 Class::MakeMethods::Emulator::accessors is based on accessors. Portions
1070 by Steve Purkis.
1071
1072 Class::MakeMethods::Emulator::AccessorFast is based on
1073 Class::Accessor::Fast. Portions Copyright 2000 Michael G Schwern.
1074
1075 Class::MakeMethods::Emulator::Inheritable is based on
1076 Class::Data::Inheritable. Portions Copyright 2000 Damian Conway and
1077 Michael G Schwern.
1078
1079 Class::MakeMethods::Emulator::mcoder is based on mcoder. Portions
1080 Copyright 2003 by Salvador Fandiño.
1081
1082 Class::MakeMethods::Emulator::Singleton is based on Class::Singleton,
1083 by Andy Wardley. Portions Copyright 1998 Canon Research Centre Europe
1084 Ltd.
1085
1086 Class::MakeMethods::Utility::Ref is based on Ref.pm. Portions Copyright
1087 1994 David Muir Sharnoff.
1088
1089 License
1090 You may use, modify, and distribute this software under the same terms
1091 as Perl.
1092
1094 Hey! The above document had some coding errors, which are explained
1095 below:
1096
1097 Around line 1582:
1098 Non-ASCII character seen before =encoding in 'Fandiño.'. Assuming
1099 CP1252
1100
1101
1102
1103perl v5.30.1 2020-01-29 MakeMethods(3)