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

NAME

6       Class::Factory - Base class for dynamic factory classes
7

SYNOPSIS

9         package My::Factory;
10         use base qw( Class::Factory );
11
12         # Add our default types
13
14         # This type is loaded when the statement is run
15
16         __PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );
17
18         # This type is loaded on the first request for type 'blech'
19
20         __PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );
21
22         1;
23
24         # Adding a new factory type in code -- 'Other::Custom::Class' is
25         # brought in via 'require' immediately
26
27         My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
28         my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
29
30         # Registering a new factory type in code; 'Other::Custom::ClassTwo'
31         # isn't brought in yet...
32
33         My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
34
35         # ...it's only 'require'd when the first instance of the type is
36         # created
37
38         my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
39
40         # Get all the loaded and registered classes and types
41
42         my @loaded_classes     = My::Factory->get_loaded_classes;
43         my @loaded_types       = My::Factory->get_loaded_types;
44         my @registered_classes = My::Factory->get_registered_classes;
45         my @registered_types   = My::Factory->get_registered_types;
46
47         # Get a registered class by it's factory type
48
49         my $registered_class = My::Factory->get_registered_class( 'type' );
50
51        # Ask the object created by the factory: Where did I come from?
52
53        my $custom_object = My::Factory->new( 'custom' );
54        print "Object was created by factory: ",
55              $custom_object->get_my_factory, " ",
56              "and is of type: ",
57              $custom_object->get_my_factory_type;
58

DESCRIPTION

60       This is a simple module that factory classes can use to generate new
61       types of objects on the fly, providing a consistent interface to common
62       groups of objects.
63
64       Factory classes are used when you have different implementations for
65       the same set of tasks but may not know in advance what implementations
66       you will be using. Configuration files are a good example of this.
67       There are four basic operations you would want to do with any configu‐
68       ration: read the file in, lookup a value, set a value, write the file
69       out. There are also many different types of configuration files, and
70       you may want users to be able to provide an implementation for their
71       own home-grown configuration format.
72
73       With a factory class this is easy. To create the factory class, just
74       subclass "Class::Factory" and create an interface for your configura‐
75       tion serializer. "Class::Factory" even provides a simple constructor
76       for you. Here's a sample interface and our two built-in configuration
77       types:
78
79        package My::ConfigFactory;
80
81        use strict;
82        use base qw( Class::Factory );
83
84        sub read  { die "Define read() in implementation" }
85        sub write { die "Define write() in implementation" }
86        sub get   { die "Define get() in implementation" }
87        sub set   { die "Define set() in implementation" }
88
89        __PACKAGE__->add_factory_type( ini  => 'My::IniReader' );
90        __PACKAGE__->add_factory_type( perl => 'My::PerlReader' );
91
92        1;
93
94       And then users can add their own subclasses:
95
96        package My::CustomConfig;
97
98        use strict;
99        use base qw( My::ConfigFactory );
100
101        sub init {
102            my ( $self, $filename, $params ) = @_;
103            if ( $params->{base_url} ) {
104                $self->read_from_web( join( '/', $params->{base_url}, $filename ) );
105            }
106            else {
107                $self->read( $filename );
108            }
109            return $self;
110        }
111
112        sub read  { ... implementation to read a file ... }
113        sub write { ... implementation to write a file ...  }
114        sub get   { ... implementation to get a value ... }
115        sub set   { ... implementation to set a value ... }
116
117        sub read_from_web { ... implementation to read via http ... }
118
119        # Now register my type with the factory
120
121        My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );
122
123        1;
124
125       (You may not wish to make your factory the same as your interface, but
126       this is an abbreviated example.)
127
128       So now users can use the custom configuration with something like:
129
130        #!/usr/bin/perl
131
132        use strict;
133        use My::ConfigFactory;
134        use My::CustomConfig;   # this adds the factory type 'custom'...
135
136        my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
137        print "Configuration is a: ", ref( $config ), "\n";
138
139       Which prints:
140
141        Configuration is a My::CustomConfig
142
143       And they can even add their own:
144
145        My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );
146
147       This might not seem like a very big win, and for small standalone
148       applications probably isn't. But when you develop large applications
149       the "(add⎪register)_factory_type()" step will almost certainly be done
150       at application initialization time, hidden away from the eyes of the
151       application developer. That developer will only know that she can
152       access the different object types as if they are part of the system.
153
154       As you see in the example above implementation for subclasses is very
155       simple -- just add "Class::Factory" to your inheritance tree and you
156       are done.
157
158       Gotchas
159
160       All type-to-class mapping information is stored under the original sub‐
161       class name. So the following will not do what you expect:
162
163        package My::Factory;
164        use base qw( Class::Factory );
165        ...
166
167        package My::Implementation;
168        use base qw( My::Factory );
169        ...
170        My::Implementation->register_factory_type( impl => 'My::Implementation' );
171
172       This does not register 'My::Implementation' under 'My::Factory' as you
173       would like, it registers the type under 'My::Implementation' because
174       that's the class we used to invoke the 'register_factory_type' method.
175       Make all "add_factory_type()" and "register_factory_type()" invocations
176       with the original factory class name and you'll be golden.
177
178       Registering Factory Types
179
180       As an additional feature, you can have your class accept registered
181       types that get brought in only when requested. This lazy loading fea‐
182       ture can be very useful when your factory offers many choices and users
183       will only need one or two of them at a time, or when some classes the
184       factory generates use libraries that some users may not have installed.
185
186       For example, say I have a factory that generates an object which parses
187       GET/POST parameters. One type uses the ubiquitous CGI module, the other
188       uses the faster but rarer Apache::Request. Many systems do not have
189       Apache::Request installed so we do not want to 'use' the module when‐
190       ever we create the factory.
191
192       Instead, we will register these types with the factory and only when
193       that type is requested will we bring that implementation in. To extend
194       our configuration example above we'll change the configuration factory
195       to use "register_factory_type()" instead of "add_factory_type()":
196
197        package My::ConfigFactory;
198
199        use strict;
200        use base qw( Class::Factory );
201
202        sub read  { die "Define read() in implementation" }
203        sub write { die "Define write() in implementation" }
204        sub get   { die "Define get() in implementation" }
205        sub set   { die "Define set() in implementation" }
206
207        __PACKAGE__->register_factory_type( ini  => 'My::IniReader' );
208        __PACKAGE__->register_factory_type( perl => 'My::PerlReader' );
209
210        1;
211
212       This way you can leave the actual inclusion of the module for people
213       who would actually use it. For our configuration example we might have:
214
215        My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
216
217       So the "My::Config::SOAP" class will only get included at the first
218       request for a configuration object of that type:
219
220        my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
221                                                     { port => 8080, ... } );
222
223       Subclassing
224
225       Piece of cake:
226
227        package My::Factory;
228        use base qw( Class::Factory );
229
230       or the old-school:
231
232        package My::Factory;
233        use Class::Factory;
234        @My::Factory::ISA = qw( Class::Factory );
235
236       You can also override two methods for logging/error handling. There are
237       a few instances where "Class::Factory" may generate a warning message,
238       or even a fatal error.  Internally, these are handled using "warn" and
239       "die", respectively.
240
241       This may not always be what you want though.  Maybe you have a differ‐
242       ent logging facility you wish to use.  Perhaps you have a more sophis‐
243       ticated method of handling errors (like Log::Log4perl.  If this is the
244       case, you are welcome to override either of these methods.
245
246       Currently, these two methods are implemented like the following:
247
248        sub factory_log   { shift; warn @_, "\n" }
249        sub factory_error { shift; die @_, "\n" }
250
251       Assume that instead of using "warn", you wish to use Log::Log4perl.
252       So, in your subclass, you might override "factory_log" like so:
253
254        sub factory_log {
255            shift;
256            my $logger = get_logger;
257            $logger->warn( @_ );
258        }
259
260       Common Usage Pattern: Initializing from the constructor
261
262       This is a very common pattern: Subclasses create an "init()" method
263       that gets called when the object is created:
264
265        package My::Factory;
266
267        use strict;
268        use base qw( Class::Factory );
269
270        1;
271
272       And here is what a subclass might look like -- note that it doesn't
273       have to subclass "My::Factory" as our earlier examples did:
274
275        package My::Subclass;
276
277        use strict;
278        use base qw( Class::Accessor );
279
280        my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
281        my @FIELDS = ( 'filename', @CONFIG_FIELDS );
282        My::Subclass->mk_accessors( @FIELDS );
283
284        # Note: we have taken the flattened C<@params> passed in and assigned
285        # the first element as C<$filename> and the other element as a
286        # hashref C<$params>
287
288        sub init {
289            my ( $self, $filename, $params ) = @_;
290            unless ( -f $filename ) {
291                die "Filename [$filename] does not exist. Object cannot be created";
292            }
293            $self->filename( filename );
294            $self->read_file_contents;
295            foreach my $field ( @CONFIG_FIELDS ) {
296                $self->{ $field } = $params->{ $field } if ( $params->{ $field } );
297            }
298            return $self;
299        }
300
301       The parent class ("My::Factory") has made as part of its definition
302       that the only parameters to be passed to the "init()" method are $file‐
303       name and $params, in that order. It could just as easily have specified
304       a single hashref parameter.
305
306       These sorts of specifications are informal and not enforced by this
307       "Class::Factory".
308
309       Registering Common Types by Default
310
311       Many times you will want the parent class to automatically register the
312       types it knows about:
313
314        package My::Factory;
315
316        use strict;
317        use base qw( Class::Factory );
318
319        My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
320        My::Factory->register_factory_type( type2 => 'My::Impl::Type2' );
321
322        1;
323
324       This allows the default types to be registered when the factory is ini‐
325       tialized. So you can use the default implementations without any more
326       registering/adding:
327
328        #!/usr/bin/perl
329
330        use strict;
331        use My::Factory;
332
333        my $impl1 = My::Factory->new( 'type1' );
334        my $impl2 = My::Factory->new( 'type2' );
335

METHODS

337       Factory Methods
338
339       new( $type, @params )
340
341       This is a default constructor you can use. It is quite simple:
342
343        sub new {
344            my ( $pkg, $type, @params ) = @_;
345            my $class = $pkg->get_factory_class( $type );
346            return undef unless ( $class );
347            my $self = bless( {}, $class );
348            return $self->init( @params );
349        }
350
351       We just create a new object as a blessed hashref of the class associ‐
352       ated (from an earlier call to "add_factory_type()" or "register_fac‐
353       tory_type()") with $type and then call the "init()" method of that
354       object. The "init()" method should return the object, or die on error.
355
356       If we do not get a class name from "get_factory_class()" we issue a
357       "factory_error()" message which typically means we throw a "die". How‐
358       ever, if you've overridden "factory_error()" and do not die, this fac‐
359       tory call will return "undef".
360
361       get_factory_class( $object_type )
362
363       Usually called from a constructor when you want to lookup a class by a
364       type and create a new object of $object_type. If $object_type is asso‐
365       ciated with a class and that class has already been included, the class
366       is returned. If $object_type is registered with a class (not yet
367       included), then we try to "require" the class. Any errors on the
368       "require" bubble up to the caller. If there are no errors, the class is
369       returned.
370
371       Returns: name of class. If a class matching $object_type is not found
372       or cannot be "require"d, then a "die()" (or more specifically, a "fac‐
373       tory_error()") is thrown.
374
375       add_factory_type( $object_type, $object_class )
376
377       Tells the factory to dynamically add a new type to its stable and
378       brings in the class implementing that type using "require". After run‐
379       ning this the factory class will be able to create new objects of type
380       $object_type.
381
382       Returns: name of class added if successful. If the proper parameters
383       are not given or if we cannot find $object_class in @INC, then we call
384       "factory_error()". A "factory_log()" message is issued if the type has
385       already been added.
386
387       register_factory_type( $object_type, $object_class )
388
389       Tells the factory to register a new factory type. This type will be
390       dynamically included (using "add_factory_type()" at the first request
391       for an instance of that type.
392
393       Returns: name of class registered if successful. If the proper parame‐
394       ters are not given then we call "factory_error()". A "factory_log()"
395       message is issued if the type has already been registered.
396
397       get_loaded_classes()
398
399       Returns a sorted list of the currently loaded classes. If no classes
400       have been loaded yet, returns an empty list.
401
402       get_loaded_types()
403
404       Returns a sorted list of the currently loaded types. If no classes have
405       been loaded yet, returns an empty list.
406
407       get_registered_classes()
408
409       Returns a sorted list of the classes that were ever registered. If no
410       classes have been registered yet, returns an empty list.
411
412       Note that a class can be both registered and loaded since we do not
413       clear out the registration once a registered class has been loaded on
414       demand.
415
416       get_registered_class( $factory_type )
417
418       Returns a registered class given a factory type.  If no class of type
419       $factory_type is registered, returns undef.  If no classes have been
420       registered yet, returns undef.
421
422       get_registered_types()
423
424       Returns a sorted list of the types that were ever registered. If no
425       types have been registered yet, returns an empty list.
426
427       Note that a type can be both registered and loaded since we do not
428       clear out the registration once a registered type has been loaded on
429       demand.
430
431       factory_log( @message )
432
433       Used internally instead of "warn" so subclasses can override. Default
434       implementation just uses "warn".
435
436       factory_error( @message )
437
438       Used internally instead of "die" so subclasses can override. Default
439       implementation just uses "die".
440
441       Implementation Methods
442
443       If your implementations -- objects the factory creates -- also inherit
444       from the factory they can do a little introspection and tell you where
445       they came from. (Inheriting from the factory is a common usage: the
446       SYNOPSIS example does it.)
447
448       All methods here can be called on either a class or an object.
449
450       get_my_factory()
451
452       Returns the factory class used to create this object or instances of
453       this class. If this class (or object class) hasn't been registered with
454       the factory it returns undef.
455
456       So with our SYNOPSIS example we could do:
457
458        my $custom_object = My::Factory->new( 'custom' );
459        print "Object was created by factory ",
460              "'", $custom_object->get_my_factory, "';
461
462       which would print:
463
464        Object was created by factory 'My::Factory'
465
466       get_my_factory_type()
467
468       Returns the type used to by the factory create this object or instances
469       of this class. If this class (or object class) hasn't been registered
470       with the factory it returns undef.
471
472       So with our SYNOPSIS example we could do:
473
474        my $custom_object = My::Factory->new( 'custom' );
475        print "Object is of type ",
476              "'", $custom_object->get_my_factory_type, "'";
477
478       which would print:
479
480        Object is of type 'custom'
481
483       Copyright (c) 2002-2006 Chris Winters. All rights reserved.
484
485       This library is free software; you can redistribute it and/or modify it
486       under the same terms as Perl itself.
487

SEE ALSO

489       "Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and John
490       Vlissides. Addison Wesley Longman, 1995. Specifically, the 'Factory
491       Method' pattern, pp. 107-116.
492

AUTHORS

494       Chris Winters <chris@cwinters.com>
495
496       Eric Andreychek <eric@openthought.net> implemented overridable
497       log/error capability and prodded the module into a simpler design.
498
499       Srdjan Jankovic <srdjan@catalyst.net.nz> contributed the idea for
500       'get_my_factory()' and 'get_my_factory_type()'
501
502       Sebastian Knapp <giftnuss@netscape.net> contributed the idea for
503       'get_registered_class()'
504
505
506
507perl v5.8.8                       2007-02-02                 Class::Factory(3)
Impressum