Class::Factory(3pm)

πŸ“¦
version 1.06 Β· 5 versions
, in ubuntu noble, ubuntu resolute, ubuntu stonking

✨ NAME ✨

okay so welcome to Class::Factory(3pm) from User Contributed Perl Documentation, bestie. πŸ’– This whole page is about Class::Factory β€” it's literally the base class for dynamic factory classes. That's the name, that's the vibe, no cap. πŸŽ€


🌈 SYNOPSIS 🌈

okay bestie, here's the synopsis and it's giving main character energy. Read the comments because they spill all the tea β˜• about when stuff gets loaded. Watch how add_factory_type loads right away while register_factory_type is lowkey patient and waits for the first request πŸ‘€.

  package My::Factory;
  use base qw( Class::Factory );

  # Add our default types

  # This type is loaded when the statement is run

  __PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );

  # This type is loaded on the first request for type 'blech'

  __PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );

  1;

  # Adding a new factory type in code -- 'Other::Custom::Class' is
  # brought in via 'require' immediately

  My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
  my $custom_object = My::Factory->new( 'custom', { this => 'that' } );

  # Registering a new factory type in code; 'Other::Custom::ClassTwo'
  # isn't brought in yet...

  My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );

  # ...it's only 'require'd when the first instance of the type is
  # created

  my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );

  # Get all the loaded and registered classes and types

  my @loaded_classes     = My::Factory->get_loaded_classes;
  my @loaded_types       = My::Factory->get_loaded_types;
  my @registered_classes = My::Factory->get_registered_classes;
  my @registered_types   = My::Factory->get_registered_types;

  # Get a registered class by it's factory type

  my $registered_class = My::Factory->get_registered_class( 'type' );

  # Ask the object created by the factory: Where did I come from?

  my $custom_object = My::Factory->new( 'custom' );
  print "Object was created by factory: ",
       $custom_object->get_my_factory, " ",
       "and is of type: ",
       $custom_object->get_my_factory_type;

  # Remove a factory type

  My::Factory->remove_factory_type('perl');

  # Unregister a factory type

  My::Factory->unregister_factory_type('blech');

not me obsessing over get_my_factory and get_my_factory_type letting the object spill where it came from πŸ’…. And yes, remove_factory_type and unregister_factory_type are there too, popping off at the end. 🫢

next up in part 2: the rest of the sections, coming at you like a new object from a factory. stay tuned bestie 🌸

πŸ’– DESCRIPTION πŸ’–

okay so bestie, here's the whole vibe: this is a simple module that factory classes can use to generate brand new types of objects on the fly, and it hands you a consistent interface to common groups of objects while it does it. ✨

So when do you even need a factory class? You reach for one when you've got different implementations for the same set of tasks, but you don't know in advance which implementations you're gonna be using. configuration files are like, the textbook example of this. there are four basic operations you'd wanna do with any configuration: read the file in, lookup a value, set a value, write the file out. and there are also SO many different types of configuration files, and maybe you want your users to be able to provide an implementation for their own home-grown configuration format. iconic of them honestly.

With a factory class this is easy. To create the factory class, just subclass Class::Factory and create an interface for your configuration serializer. Class::Factory even provides a simple constructor for you. Here's a sample interface and our two built-in configuration types:

package My::ConfigFactory;

use strict;
use base qw( Class::Factory );

sub read  { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get   { die "Define get() in implementation" }
sub set   { die "Define set() in implementation" }

__PACKAGE__->add_factory_type( ini  => 'My::IniReader' );
__PACKAGE__->add_factory_type( perl => 'My::PerlReader' );

1;

and then bestie, users can add their own subclasses:

package My::CustomConfig;

use strict;
use base qw( My::ConfigFactory );

sub init {
    my ( $self, $filename, $params ) = @_;
    if ( $params->{base_url} ) {
        $self->read_from_web( join( '/', $params->{base_url}, $filename ) );
    }
    else {
        $self->read( $filename );
    }
    return $self;
}

sub read  { ... implementation to read a file ... }
sub write { ... implementation to write a file ...  }
sub get   { ... implementation to get a value ... }
sub set   { ... implementation to set a value ... }

sub read_from_web { ... implementation to read via http ... }

# Now register my type with the factory

My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );

1;
(You may not wish to make your factory the same as your interface, but this is an abbreviated example.)

So now users can use the custom configuration with something like:

#!/usr/bin/perl

use strict;
use My::ConfigFactory;
use My::CustomConfig;   # this adds the factory type 'custom'...

my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
print "Configuration is a: ", ref( $config ), "\n";

Which prints:

Configuration is a My::CustomConfig

And they can even add their own:

My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );

ngl this might not seem like a very big win, and for small standalone applications it probably isn't. But when you develop large applications, the (add|register)_factory_type() step will almost certainly be done at application initialization time, hidden away from the eyes of the application developer. That developer will only know that she can access the different object types as if they are part of the system. like, the magic is just there for her πŸͺ„

As you see in the example above, implementation for subclasses is very simple β€” just add Class::Factory to your inheritance tree and you are done. periodt.


🚨 Gotchas 🚨

All type-to-class mapping information is stored under the original subclass name. So the following will not do what you expect:

package My::Factory;
use base qw( Class::Factory );
...

package My::Implementation;
use base qw( My::Factory );
...
My::Implementation->register_factory_type( impl => 'My::Implementation' );

This does not register 'My::Implementation' under 'My::Factory' as you would like, it registers the type under 'My::Implementation' because that's the class we used to invoke the 'register_factory_type' method. So make all add_factory_type() and register_factory_type() invocations with the original factory class name and you'll be golden. πŸ’…


πŸ“¦ Registering Factory Types πŸ“¦

As an additional feature, you can have your class accept registered types that get brought in only when requested. This lazy loading feature can be very useful when your factory offers many choices and users will only need one or two of them at a time, or when some classes the factory generates use libraries that some users may not have installed. it's giving "don't load what you don't need" πŸ’€

For example, say I have a factory that generates an object which parses GET/POST parameters. One type uses the ubiquitous CGI module, the other uses the faster but rarer Apache::Request. Many systems do not have Apache::Request installed so we do not want to 'use' the module whenever we create the factory.

Instead, we will register these types with the factory and only when that type is requested will we bring that implementation in. To extend our configuration example above we'll change the configuration factory to use register_factory_type() instead of add_factory_type():

package My::ConfigFactory;

use strict;
use base qw( Class::Factory );

sub read  { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get   { die "Define get() in implementation" }
sub set   { die "Define set() in implementation" }

__PACKAGE__->register_factory_type( ini  => 'My::IniReader' );
__PACKAGE__->register_factory_type( perl => 'My::PerlReader' );

1;

This way you can leave the actual inclusion of the module for people who would actually use it. For our configuration example we might have:

My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );

So the My::Config::SOAP class will only get included at the first request for a configuration object of that type:

my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
                                             { port => 8080, ... } );

🧬 Subclassing 🧬

Piece of cake 🍰:

package My::Factory;
use base qw( Class::Factory );

or the old-school:

package My::Factory;
use Class::Factory;
@My::Factory::ISA = qw( Class::Factory );

You can also override two methods for logging/error handling. There are a few instances where Class::Factory may generate a warning message, or even a fatal error. Internally, these are handled using warn and die, respectively.

This may not always be what you want though. Maybe you have a different logging facility you wish to use. Perhaps you have a more sophisticated method of handling errors (like Log::Log4perl. If this is the case, you are welcome to override either of these methods. 🫢

Currently, these two methods are implemented like the following:

sub factory_log   { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }

Assume that instead of using warn, you wish to use Log::Log4perl. So, in your subclass, you might override factory_log like so:

sub factory_log {
    shift;
    my $logger = get_logger;
    $logger->warn( @_ );
}

🌸 Common Usage Pattern: Initializing from the constructor 🌸

This is a very common pattern: Subclasses create an init() method that gets called when the object is created:

package My::Factory;

use strict;
use base qw( Class::Factory );

1;

And here is what a subclass might look like β€” note that it doesn't have to subclass My::Factory as our earlier examples did:

package My::Subclass;

use strict;
use base qw( Class::Accessor );

my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );

# Note: we have taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>

sub init {
    my ( $self, $filename, $params ) = @_;
    unless ( -f $filename ) {
        die "Filename [$filename] does not exist. Object cannot be created";
    }
    $self->filename( filename );
    $self->read_file_contents;
    foreach my $field ( @CONFIG_FIELDS ) {
        $self->{ $field } = $params->{ $field } if ( $params->{ $field } );
    }
    return $self;
}

The parent class (My::Factory) has made as part of its definition that the only parameters to be passed to the init() method are $filename and $params, in that order. It could just as easily have specified a single hashref parameter.

These sorts of specifications are informal and not enforced by this Class::Factory. so like, it's a vibe, not a rulebook, iykyk πŸ’œ


πŸ‘‘ Registering Common Types by Default πŸ‘‘

Many times you will want the parent class to automatically register the types it knows about:

package My::Factory;

use strict;
use base qw( Class::Factory );

My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
My::Factory->register_factory_type( type2 => 'My::Impl::Type2' );

1;

This allows the default types to be registered when the factory is initialized. So you can use the default implementations without any more registering/adding:

#!/usr/bin/perl

use strict;
use My::Factory;

my $impl1 = My::Factory->new( 'type1' );
my $impl2 = My::Factory->new( 'type2' );

πŸ’– METHODS πŸ’–

✨ Factory Methods ✨

  • new( $type, @params ) β€” the default constructor, and bestie it is so simple, look:
sub new {
    my ( $pkg, $type, @params ) = @_;
    my $class = $pkg->get_factory_class( $type );
    return undef unless ( $class );
    my $self = bless( {}, $class );
    return $self->init( @params );
}

We literally just bless a new object β€” a hashref, as one does β€” into the class that got associated with $type way back when (like, from an earlier call to add_factory_type() or register_factory_type(), iykyk), and then we call that object's init() method. And here's the vibe check: init() should return the object, or it can die on error. No half-sending, no ghosting 🩻.

Now β€” if get_factory_class() hands us back nothing (no class name, awkward 😭), we send a factory_error() message, which typically means we just throw a die. But listen: if you've overridden factory_error() and it doesn't die, then this factory call returns undef instead. No big dramatic exit, just… nothing. πŸ’€

  • get_factory_class( $object_type ) β€” you'll usually call this from a constructor when you want to look up a class by a type and then create a new object of $object_type. So here's the tea β˜•: if $object_type is already associated with a class and that class has already been included, we return the class, done, easy. If $object_type is registered with a class that's not yet included, we try to require it. Any errors on that require bubble straight up to whoever called us (sorry not sorry πŸ™ˆ). If there are no errors, you get the class back. Returns: the name of the class. And if a class matching $object_type isn't found, or it just cannot be required? Then a die() gets thrown β€” or more specifically, a factory_error(). 🚨
  • add_factory_type( $object_type, $object_class ) β€” tells the factory to dynamically add a new type to its stable, and brings in the class that implements that type using require. After you run this, the factory class can make brand new objects of type $object_type. Glow up complete ✨ Returns: the name of the class added, if it worked. But if the proper parameters aren't given, or we can't find $object_class in @INC, we call factory_error(). And if the type was already added? You get a factory_log() message. (Not me adding it twice πŸ™ˆ)
  • register_factory_type( $object_type, $object_class ) β€” tells the factory to register a new factory type. This type gets dynamically included (via add_factory_type(), cute) at the first request for an instance of that type. Lazy loading but make it fashion πŸ’… Returns: the name of the class registered, if it worked. If the proper parameters aren't given, we call factory_error(). And a factory_log() message fires off if the type was already registered.
  • remove_factory_type( @object_types ) β€” removes a factory type from the factory. It's the exact opposite of add_factory_type(). No return value. Bye felicia πŸ‘‹

Removing a factory type is useful when a subclass of the factory wants to redefine the mapping for that factory type. Because plot twist: add_factory_type() does not allow overriding a factory type, so you have to remove it first. Rules are rules, bestie.

  • unregister_factory_type( @object_types ) β€” unregisters a factory type from the factory. This is the exact opposite of register_factory_type(). No return value.

Same deal: unregistering a factory type is useful if a subclass of the factory wants to redefine the mapping for the factory type. register_factory_type() doesn't allow overriding a factory type either, so you have to unregister it first. Order of operations, always. πŸ”₯

  • get_factory_type_for( $class ) β€” takes an object or a class name string, and returns the factory type used to construct that class. Returns undef if there's no such factory type. Mystery solved πŸ”
  • get_loaded_classes() β€” returns a sorted list of the currently loaded classes. If no classes have been loaded yet, you get an empty list. Empty. Void. Nothing. πŸ«₯
  • get_loaded_types() β€” returns a sorted list of the currently loaded types. If no classes have been loaded yet, it returns an empty list.
  • get_registered_classes() β€” returns a sorted list of the classes that were ever registered. If no classes have been registered yet, empty list, we love a clean slate 🌸
Heads up: a class can be both registered and loaded, because we do not clear out the registration once a registered class has been loaded on demand. Both things are true at once. Multitasking queen πŸ‘‘
  • get_registered_class( $factory_type ) β€” returns a registered class given a factory type. If no class of type $factory_type is registered, returns undef. If no classes have been registered yet, returns undef. So many undefs 😭
  • get_registered_types() β€” returns a sorted list of the types that were ever registered. If no types have been registered yet, returns an empty list.
Same note as before, no cap: a type can be both registered and loaded, since we do not clear out the registration once a registered type has been loaded on demand.
  • factory_log( @message ) β€” used internally instead of warn, specifically so subclasses can override it. The default implementation just uses warn. Nothing fancy, it's giving honest work πŸŽ€
  • factory_error( @message ) β€” used internally instead of die, again so subclasses can override. The default implementation just uses die. The drama is built in πŸ’€

🌈 Implementation Methods 🌈

If your implementations β€” as in, the objects the factory creates β€” also inherit from the factory, they can do a little introspection and tell you exactly where they came from. And ngl, inheriting from the factory is a super common usage: the SYNOPSIS example literally does it. Main character behavior fr fr πŸ’…

All methods here can be called on either a class or an object. Flexible. Iconic. ✨

  • get_my_factory() β€” returns the factory class used to create this object, or instances of this class. And if this class (or object class) hasn't been registered with the factory? It returns undef. 🫠

So with our SYNOPSIS example we could do:

my $custom_object = My::Factory->new( 'custom' );
print "Object was created by factory ",
      "'", $custom_object->get_my_factory, "';

which would print:

Object was created by factory 'My::Factory'
  • get_my_factory_type() β€” returns the type used by the factory to create this object, or instances of this class. Same deal: if this class (or object class) hasn't been registered with the factory, it returns undef.

So with our SYNOPSIS example we could do:

my $custom_object = My::Factory->new( 'custom' );
print "Object is of type ",
      "'", $custom_object->get_my_factory_type, "'";

which would print:

Object is of type 'custom'

Copyright (c) 2002-2007 Chris Winters. All rights reserved. 🫢

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


πŸ‘€ SEE ALSO πŸ‘€

"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. Addison Wesley Longman, 1995. Specifically, the 'Factory Method' pattern, pp. 107-116. The lore πŸ“š


🌟 AUTHORS 🌟

  • Fred Moyer <fred@redhotpenguin.com> is the current maintainer. πŸ‘‘
  • Chris Winters <chris@cwinters.com>
  • Eric Andreychek <eric@openthought.net> implemented the overridable log/error capability and prodded the module into a simpler design. A true icon πŸ› οΈ
  • Srdjan Jankovic <srdjan@catalyst.net.nz> contributed the idea for get_my_factory() and get_my_factory_type()
  • Sebastian Knapp <giftnuss@netscape.net> contributed the idea for get_registered_class()
  • Marcel Gruenauer <marcel@cpan.org> contributed the methods remove_factory_type() and unregister_factory_type().

and that's the whole page bestie, you made it to the end πŸŽ‰ This one ships as part of perl v5.36.0, dated 2022-10-13, and it lives at Class::Factory(3pm) β€” go build something cute with it πŸ’–πŸ¦‹πŸŒΈ

πŸ“¦ where this page comes from