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

NAME

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

SYNOPSIS

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

DESCRIPTION

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

METHODS

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

SEE ALSO

316       Params::Validate
317

AUTHOR

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