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

SEE ALSO

319       Params::Validate
320

AUTHOR

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