1Class::Container(3)   User Contributed Perl Documentation  Class::Container(3)
2
3
4

NAME

6       Class::Container - Glues object frameworks together transparently
7

VERSION

9       version 0.13
10

SYNOPSIS

12        package Car;
13        use Class::Container;
14        @ISA = qw(Class::Container);
15
16        __PACKAGE__->valid_params
17          (
18           paint  => {default => 'burgundy'},
19           style  => {default => 'coupe'},
20           windshield => {isa => 'Glass'},
21           radio  => {isa => 'Audio::Device'},
22          );
23
24        __PACKAGE__->contained_objects
25          (
26           windshield => 'Glass::Shatterproof',
27           wheel      => { class => 'Vehicle::Wheel',
28                           delayed => 1 },
29           radio      => 'Audio::MP3',
30          );
31
32        sub new {
33          my $package = shift;
34
35          # 'windshield' and 'radio' objects are created automatically by
36          # SUPER::new()
37          my $self = $package->SUPER::new(@_);
38
39          $self->{right_wheel} = $self->create_delayed_object('wheel');
40          ... do any more initialization here ...
41          return $self;
42        }
43

DESCRIPTION

45       This class facilitates building frameworks of several classes that
46       inter-operate.  It was first designed and built for "HTML::Mason", in
47       which the Compiler, Lexer, Interpreter, Resolver, Component, Buffer,
48       and several other objects must create each other transparently, passing
49       the appropriate parameters to the right class, possibly substituting
50       other subclasses for any of these objects.
51
52       The main features of "Class::Container" are:
53
54       •   Explicit declaration of containment relationships (aggregation,
55           factory creation, etc.)
56
57       •   Declaration of constructor parameters accepted by each member in a
58           class framework
59
60       •   Transparent passing of constructor parameters to the class that
61           needs them
62
63       •   Ability to create one (automatic) or many (manual) contained
64           objects automatically and transparently
65
66   Scenario
67       Suppose you've got a class called "Parent", which contains an object of
68       the class "Child", which in turn contains an object of the class
69       "GrandChild".  Each class creates the object that it contains.  Each
70       class also accepts a set of named parameters in its new() method.
71       Without using "Class::Container", "Parent" will have to know all the
72       parameters that "Child" takes, and "Child" will have to know all the
73       parameters that "GrandChild" takes.  And some of the parameters
74       accepted by "Parent" will really control aspects of "Child" or
75       "GrandChild".  Likewise, some of the parameters accepted by "Child"
76       will really control aspects of "GrandChild".  So, what happens when you
77       decide you want to use a "GrandDaughter" class instead of the generic
78       "GrandChild"?  "Parent" and "Child" must be modified accordingly, so
79       that any additional parameters taken by "GrandDaughter" can be
80       accommodated.  This is a pain - the kind of pain that object-oriented
81       programming was supposed to shield us from.
82
83       Now, how can "Class::Container" help?  Using "Class::Container", each
84       class ("Parent", "Child", and "GrandChild") will declare what arguments
85       they take, and declare their relationships to the other classes
86       ("Parent" creates/contains a "Child", and "Child" creates/contains a
87       "GrandChild").  Then, when you create a "Parent" object, you can pass
88       "Parent->new()" all the parameters for all three classes, and they will
89       trickle down to the right places.  Furthermore, "Parent" and "Child"
90       won't have to know anything about the parameters of its contained
91       objects.  And finally, if you replace "GrandChild" with
92       "GrandDaughter", no changes to "Parent" or "Child" will likely be
93       necessary.
94

METHODS

96   new()
97       Any class that inherits from "Class::Container" should also inherit its
98       new() method.  You can do this simply by omitting it in your class, or
99       by calling SUPER::new(@_) as indicated in the SYNOPSIS.  The new()
100       method ensures that the proper parameters and objects are passed to the
101       proper constructor methods.
102
103       At the moment, the only possible constructor method is new().  If you
104       need to create other constructor methods, they should call new()
105       internally.
106
107   __PACKAGE__->contained_objects()
108       This class method is used to register what other objects, if any, a
109       given class creates.  It is called with a hash whose keys are the
110       parameter names that the contained class's constructor accepts, and
111       whose values are the default class to create an object of.
112
113       For example, consider the "HTML::Mason::Compiler" class, which uses the
114       following code:
115
116         __PACKAGE__->contained_objects( lexer => 'HTML::Mason::Lexer' );
117
118       This defines the relationship between the "HTML::Mason::Compiler" class
119       and the class it creates to go in its "lexer" slot.  The
120       "HTML::Mason::Compiler" class "has a" "lexer".  The
121       "HTML::Mason::Compiler->new()" method will accept a "lexer" parameter
122       and, if no such parameter is given, an object of the
123       "HTML::Mason::Lexer" class should be constructed.
124
125       We implement a bit of magic here, so that if
126       "HTML::Mason::Compiler->new()" is called with a "lexer_class"
127       parameter, it will load the indicated class (presumably a subclass of
128       "HTML::Mason::Lexer"), instantiate a new object of that class, and use
129       it for the Compiler's "lexer" object.  We're also smart enough to
130       notice if parameters given to "HTML::Mason::Compiler->new()" actually
131       should go to the "lexer" contained object, and it will make sure that
132       they get passed along.
133
134       Furthermore, an object may be declared as "delayed", which means that
135       an object won't be created when its containing class is constructed.
136       Instead, these objects will be created "on demand", potentially more
137       than once.  The constructors will still enjoy the automatic passing of
138       parameters to the correct class.  See the create_delayed_object() for
139       more.
140
141       To declare an object as "delayed", call this method like this:
142
143         __PACKAGE__->contained_objects( train => { class => 'Big::Train',
144                                                    delayed => 1 } );
145
146   __PACKAGE__->valid_params(...)
147       Specifies the parameters accepted by this class's new() method as a set
148       of key/value pairs.  Any parameters accepted by a superclass/subclass
149       will also be accepted, as well as any parameters accepted by contained
150       objects.  This method is a get/set accessor method, so it returns a
151       reference to a hash of these key/value pairs.  As a special case, if
152       you wish to set the valid params to an empty set and you previously set
153       it to a non-empty set, you may call "__PACKAGE__->valid_params(undef)".
154
155       valid_params() is called with a hash that contains parameter names as
156       its keys and validation specifications as values.  This validation
157       specification is largely the same as that used by the
158       "Params::Validate" module, because we use "Params::Validate"
159       internally.
160
161       As an example, consider the following situation:
162
163         use Class::Container;
164         use Params::Validate qw(:types);
165         __PACKAGE__->valid_params
166             (
167              allow_globals        => { type => ARRAYREF, parse => 'list',   default => [] },
168              default_escape_flags => { type => SCALAR,   parse => 'string', default => '' },
169              lexer                => { isa => 'HTML::Mason::Lexer' },
170              preprocess           => { type => CODEREF,  parse => 'code',   optional => 1 },
171              postprocess_perl     => { type => CODEREF,  parse => 'code',   optional => 1 },
172              postprocess_text     => { type => CODEREF,  parse => 'code',   optional => 1 },
173             );
174
175         __PACKAGE__->contained_objects( lexer => 'HTML::Mason::Lexer' );
176
177       The "type", "default", and "optional" parameters are part of the
178       validation specification used by "Params::Validate".  The various
179       constants used, "ARRAYREF", "SCALAR", etc. are all exported by
180       "Params::Validate".  This means that any of these six parameter names,
181       plus the "lexer_class" parameter (because of the contained_objects()
182       specification given earlier), are valid arguments to the Compiler's
183       new() method.
184
185       Note that there are also some "parse" attributes declared.  These have
186       nothing to do with "Class::Container" or "Params::Validate" - any extra
187       entries like this are simply ignored, so you are free to put extra
188       information in the specifications as long as it doesn't overlap with
189       what "Class::Container" or "Params::Validate" are looking for.
190
191   $self->create_delayed_object()
192       If a contained object was declared with "delayed => 1", use this method
193       to create an instance of the object.  Note that this is an object
194       method, not a class method:
195
196          my $foo =       $self->create_delayed_object('foo', ...); # YES!
197          my $foo = __PACKAGE__->create_delayed_object('foo', ...); # NO!
198
199       The first argument should be a key passed to the contained_objects()
200       method.  Any additional arguments will be passed to the new() method of
201       the object being created, overriding any parameters previously passed
202       to the container class constructor.  (Could I possibly be more
203       alliterative?  Veni, vedi, vici.)
204
205   $self->delayed_object_params($name, [params])
206       Allows you to adjust the parameters that will be used to create any
207       delayed objects in the future.  The first argument specifies the "name"
208       of the object, and any additional arguments are key-value pairs that
209       will become parameters to the delayed object.
210
211       When called with only a $name argument and no list of parameters to
212       set, returns a hash reference containing the parameters that will be
213       passed when creating objects of this type.
214
215   $self->delayed_object_class($name)
216       Returns the class that will be used when creating delayed objects of
217       the given name.  Use this sparingly - in most situations you shouldn't
218       care what the class is.
219
220   __PACKAGE__->decorates()
221       Version 0.09 of Class::Container added [as yet experimental] support
222       for so-called "decorator" relationships, using the term as defined in
223       Design Patterns by Gamma, et al. (the Gang of Four book).  To declare a
224       class as a decorator of another class, simply set @ISA to the class
225       which will be decorated, and call the decorator class's decorates()
226       method.
227
228       Internally, this will ensure that objects are instantiated as
229       decorators.  This means that you can mix & match extra add-on
230       functionality classes much more easily.
231
232       In the current implementation, if only a single decoration is used on
233       an object, it will be instantiated as a simple subclass, thus avoiding
234       a layer of indirection.
235
236   $self->validation_spec()
237       Returns a hash reference suitable for passing to the "Params::Validate"
238       "validate" function.  Does not include any arguments that can be passed
239       to contained objects.
240
241   $class->allowed_params(\%args)
242       Returns a hash reference of every parameter this class will accept,
243       including parameters it will pass on to its own contained objects.  The
244       keys are the parameter names, and the values are their corresponding
245       specifications from their valid_params() definitions.  If a parameter
246       is used by both the current object and one of its contained objects,
247       the specification returned will be from the container class, not the
248       contained.
249
250       Because the parameters accepted by new() can vary based on the
251       parameters passed to new(), you can pass any parameters to the
252       allowed_params() method too, ensuring that the hash you get back is
253       accurate.
254
255   $self->container()
256       Returns the object that created you.  This is remembered by storing a
257       reference to that object, so we use the "Scalar::Utils" weakref()
258       function to avoid persistent circular references that would cause
259       memory leaks.  If you don't have "Scalar::Utils" installed, we don't
260       make these references in the first place, and calling container() will
261       result in a fatal error.
262
263       If you weren't created by another object via "Class::Container",
264       container() returns "undef".
265
266       In most cases you shouldn't care what object created you, so use this
267       method sparingly.
268
269   $object->show_containers
270   $package->show_containers
271       This method returns a string meant to describe the containment
272       relationships among classes.  You should not depend on the specific
273       formatting of the string, because I may change things in a future
274       release to make it prettier.
275
276       For example, the HTML::Mason code returns the following when you do
277       "$interp->show_containers":
278
279        HTML::Mason::Interp=HASH(0x238944)
280          resolver -> HTML::Mason::Resolver::File
281          compiler -> HTML::Mason::Compiler::ToObject
282            lexer -> HTML::Mason::Lexer
283          request -> HTML::Mason::Request (delayed)
284            buffer -> HTML::Mason::Buffer (delayed)
285
286       Currently, containment is shown by indentation, so the Interp object
287       contains a resolver and a compiler, and a delayed request (or several
288       delayed requests).  The compiler contains a lexer, and each request
289       contains a delayed buffer (or several delayed buffers).
290
291   $object->dump_parameters
292       Returns a hash reference containing a set of parameters that should be
293       sufficient to re-create the given object using its class's new()
294       method.  This is done by fetching the current value for each declared
295       parameter (i.e. looking in $object for hash entries of the same name),
296       then recursing through all contained objects and doing the same.
297
298       A few words of caution here.  First, the dumped parameters represent
299       the current state of the object, not the state when it was originally
300       created.
301
302       Second, a class's declared parameters may not correspond exactly to its
303       data members, so it might not be possible to recover the former from
304       the latter.  If it's possible but requires some manual fudging, you can
305       override this method in your class, something like so:
306
307        sub dump_parameters {
308          my $self = shift;
309          my $dump = $self->SUPER::dump_parameters();
310
311          # Perform fudgery
312          $dump->{incoming} = $self->{_private};
313          delete $dump->{superfluous};
314          return $dump;
315        }
316

SEE ALSO

318       Params::Validate
319

AUTHOR

321       Originally by Ken Williams <ken@mathforum.org> and Dave Rolsky
322       <autarch@urth.org> for the HTML::Mason project.  Important feedback
323       contributed by Jonathan Swartz <swartz@pobox.com>.  Extended by Ken
324       Williams for the AI::Categorizer project.
325
326       Currently maintained by Ken Williams.
327
329       This program is free software; you can redistribute it and/or modify it
330       under the same terms as Perl itself.
331
332
333
334perl v5.36.0                      2023-01-20               Class::Container(3)
Impressum