| Badger documentation | Contained in the Badger distribution. |
Badger::Hub - central repository of shared resources
use Badger::Hub;
# do the happy badger dance!
This documentation describes the Badger::Hub object. A hub sits in the
middle of a Badger application, providing a central point of access to
the various other modules, components and sub-system that an application
uses.
You generally don't need to worry about the Badger::Hub if you're just
a casual user of the Badger modules. It will primarily be of interest
to developers who are building their own badger-powered applications or
extensions.
At present this module is quite basic. It will be developed further in due course.
A Badger::Hub object is a central repository of shared resources for a
Badger application. The hub sits in the middle of an application and
provides access to all the individual components and larger sub-systems
that may be required. It automatically loads and instantiates these other
modules on demand and caches then for subsequent use.
The Badger::Hub base class currently has two components:
filesystem => Badger::Filesystem
codecs => Badger::Codecs
An AUTOLOAD method allows you to access any component by name. It will
be loaded and instantiated automatically. The AUTOLOAD method also
generates the missing method so that you can avoid the overhead of the
AUTOLOAD method the next time you call it.
my $filesystem = $hub->filesystem;
You can add your own component to a hub and they will be available in the same way.
$hub->components( fuzzbox => 'My::Module::Fuzzbox' );
my $fuzzbox = $hub->fuzzbox;
As well as accessing components directly, you can also make use of delegate
methods that get forwarded onto a component. For example, the hub file()
method is just a short cut to the file() method of the filesystem
component (implemented by Badger::Filesystem).
$file = $hub->file('/path/to/file'); # the short cut
$file = $hub->filesystem->file('/path/to/file'); # the long way
You can easily define your own delegate methods.
$hub->delegates( warm_fuzz => 'fuzzbox' );
$fuzzed = $hub->warm_fuzz; # the short way
$fuzzed = $hub->fuzzbox->warm_fuzz; # the long way.
You can subclass Badger::Hub to define your own collection of components and delegate methods, as shown in the example below.
package My::Hub;
use Badger::Class
version => 0.01,
debug => 0,
base => 'Badger::Hub';
our $COMPONENTS = {
fuzzbox => 'My::Module::Fuzzbox',
flanger => 'My::Module::Flanger',
};
our $DELEGATES = {
warm_fuzz => 'fuzzbox',
dirty_noise => 'fuzzbox',
wide_flange => 'flanger',
wet_flange => 'flanger',
};
In some cases, sub-systems instantiated by a Badger::Hub will also maintain a reference back to the hub. This allows them to access other sub-systems and components that they require.
Note that this behaviour implicitly creates circular references between the hub and its delegates. This is intentional. It ensures that the hub and delegates keep each other alive until the hub is explicitly destroyed and the references are freed. Having the hub stick around for as long as possible is usually a Good Thing. It acts as a singleton providing a central point of access to the resources that your application uses (which is a fancy way of saying it's like a global variable).
+-----+ +-----------+
| HUB |----->| COMPONENT |
| |<-----| |
+-----+ +-----------+
If you manually create a hub for whatever reason (and the cases where you would need to are few and far between) then you are responsible for calling the destroy() method when you're done with it. This will manually break the circular references and free up any memory used by the hub and any delegates it is using. If you don't call the destroy() method then the hub will remain alive until the end of the program when the memory will be freed as usual. In most cases this is perfectly acceptable.
However, you generally don't need to worry about any of this because you
wouldn't normally create a hub manually. Instead, you would leave it up to the
Badger façade (or "front-end") module to do that behind the scenes. When
you create a Badger module it implicitly creates a Badger::Hub to use.
When the Badger object goes out of scope its DESTROY method
automatically calls the hub's destroy method.
sub foo {
my $badger = Badger->new;
my $hub = $badger->hub;
# do something
# $badger object is freed here, that calls $hub->destroy
}
Because there is no reference from the hub back to the Badger façade object you don't have to worry about circular references. The Badger object is correctly freed and that ensures the hub gets cleaned up.
+--------+ +-----+ +-----------+
| BADGER |----->| HUB |----->| COMPONENT |
| | | |<-----| |
+--------+ +-----+ +-----------+
If you call Badger methods as class methods then they are forwarded to
a prototype object (effectively a singleton object).
That in turn will use a prototype hub object. In this
case, both the Badger and Badger::Hub objects will exist until the
end of the program. This ensures that your class methods all Do the right
Thing without you having to worry about creating a Badger object.
# class method creates Badger prototype, which creates Badger::Hub
# prototype, which loads, instantiates and caches Badger::Filesystem
# which can then fetch the file
my $file = Badger->file('/path/to/file');
# later... reuse same Badger, Badger::Hub and Badger::Filesystem
my $dir = Badger->dir('/path/to/dir');
Constructor method used to create a new hub object.
$hub = Badger::Hub->new();
This method can be used to get or set entries in the components table for the hub. Components are other modules that the hub can delegate to.
# get components hash ref
my $comps = $hub->components;
# add new components
$hub->components({
fuzzbox => 'My::Module::Fuzzbox',
flanger => 'My::Module::Flanger',
});
This method returns a single entry from the components table.
print $hub->component('fuzzbox'); # My::Module::Fuzzbox
This method can be used to get or set entries in the delegates table for the hub. This specifies which hub methods should be delegated to components.
# get delegates hash ref
my $delegs = $hub->delegates;
# add new delegates
$hub->delegates({
warm_fuzz => 'fuzzbox',
dirty_noise => 'fuzzbox',
wide_flange => 'flanger',
wet_flange => 'flanger',
});
This method returns a single entry from the delegates table.
print $hub->delegate('warm_fuzz'); # fuzzbox
This method can be manually called to destroy the hub and any components that it is using.
This method configures and instantiates a component. The first argument is the
component name. This is mapped to a module via the component() method and
the module is loaded. A list of named parameters, or a reference to a hash
array of named paramters may follow. A reference to the hub is added to these
as the hub item before forwarding them to the constructor method for the
component. The component is then cached for subsequent use.
# calling the configure() method like this...
$hub->configure( fuzzbox => { volume => 11 } );
# ...results in code equivalent to this:
use Your::Module::Fuzzbox;
Your::Module::Fuzzbox->new({ volume => 11, hub => $hub });
This method generates a component method named $name which accesses an
instance of the $module component module.
This method generates a delegate method named $name which delegates to
the $name method of the $component component.
This method returns a reference to a Badger::Config object representing the configuration for the hub. This is still marked experimental.
Andy Wardley http://wardley.org/
Copyright (C) 2001-2009 Andy Wardley. All Rights Reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| Badger documentation | Contained in the Badger distribution. |
#======================================================================== # # Badger::Hub # # DESCRIPTION # A hub provides a central configuration and management point for # Badger components to access other Badger components. # # AUTHOR # Andy Wardley <abw@wardley.org> # #======================================================================== package Badger::Hub; use Badger::Class version => 0.01, debug => 0, base => 'Badger::Prototype', import => 'class', constants => 'HASH ARRAY REFS PKG', words => 'COMPONENTS DELEGATES COMP_CACHE DELG_CACHE', messages => { no_module => 'No %s module defined.', bad_method => "Invalid method '%s' called on %s at %s line %s", }; use Badger::Config; our $CONFIG = 'Badger::Config'; our $COMPONENTS = { pod => 'Badger::Pod', codecs => 'Badger::Codecs', filesystem => 'Badger::Filesystem', }; our $DELEGATES = { file => 'filesystem', # hub->file ==> hub->filesystem->file directory => 'filesystem', dir => 'filesystem', codec => 'codecs', pod => 'pod', }; our $LOADED = { }; our $AUTOLOAD; sub init { my ($self, $args) = @_; # We're looking for a specific 'config' item which the user can provide to # points to a master configuration object or class name. We default to the # value in the $CONFIG package variable, which in this case is Badger::Config, # but could be re-defined by a subclass to be something else. my $config = delete($args->{ config }) || $self->class->any_var('CONFIG'); class($config)->load unless ref $config; $config = $config->new($args) unless blessed $config; $self->{ config } = $config; $self->debug("hub config: $self->{ config }\n") if $DEBUG; return $self; } sub config { my $self = shift; $self = $self->prototype(@_) unless ref $self; return $self->{ config }; } sub components { my $self = shift; my $class = $self->class; my $comps = $class->var(COMP_CACHE) || $class->var(COMP_CACHE => $class->hash_vars(COMPONENTS)); if (@_) { my $args = ref $_[0] eq HASH ? shift : { @_ }; @$comps{ keys %$args } = values %$args; } return $comps; } sub component { my $self = shift; my $name = shift; $self->components->{ $name }; } sub delegates { my $self = shift; my $class = $self->class; my $delgs = $class->var(DELG_CACHE) || $class->var(DELG_CACHE => $class->hash_vars(DELEGATES)); if (@_) { my $args = ref $_[0] eq HASH ? shift : { @_ }; @$delgs{ keys %$args } = values %$args; } return $delgs; } sub delegate { my ($self, $name) = @_; $self->delegates->{ $name }; } sub generate_component_method { my ($self, $name, $comp) = @_; my $class = ref $self || $self; no strict REFS; $LOADED->{ $name } ||= class($comp)->load; unless (defined &{$class.PKG.$name}) { $class->debug("generating $name() in $class\n") if $DEBUG; *{$class.PKG.$name} = sub { my $self = shift; my $args = @_ && ref $_[0] eq HASH ? shift : { @_ }; $self = $self->prototype() unless ref $self; return $self->{ $name } ||= $self->configure( $name => { # TODO: figure out what's going on here in terms of # possible combinations of configuration options %$args, hub => $self, module => $comp } ); }; } } sub generate_delegate_method { my ($self, $name, $deleg) = @_; my $class = ref $self || $self; no strict REFS; # foo => bar is mapped to $self->bar->foo # foo => [bar, baz] is mapped to $self->bar->baz my ($m1, $m2) = ref $deleg eq ARRAY ? @$deleg : ($deleg, $name); unless (defined &{$class.PKG.$name}) { $class->debug("generating $name() in $class\n") if $DEBUG; *{$class.PKG.$name} = sub { shift->$m1->$m2(@_); }; } } sub AUTOLOAD { my ($self, @args) = @_; my ($name) = ($AUTOLOAD =~ /([^:]+)$/ ); return if $name eq 'DESTROY'; my ($comp, $deleg); $self->debug("AUTOLOAD $name\n") if $DEBUG; # upgrade class methods to calls on prototype $self = $self->prototype unless ref $self; if ($comp = $self->component($name)) { $self->debug("Found component: $name\n") if $DEBUG; $self->generate_component_method($name => $comp); $self->debug("Calling $self->$name(", join(',', @args), ")\n") if $DEBUG; return $self->$name(@args); } elsif ($deleg = $self->delegate($name)) { $self->debug("Found delegate: $name\n") if $DEBUG; $self->generate_delegate_method($name => $deleg); $self->debug("Calling $self->$name(", join(',', @args), ")\n") if $DEBUG; return $self->$name(@args); } return $self->error_msg( bad_method => $name, ref $self, (caller())[1,2] ); } # Configure and create a sub-component identified by $name, using # any configuration items in $params and any values defined locally # in a configuration hash, object or class. # # The $self->{ config } can contain a hash array of configuration # items, or it can be a Badger::Config object or the class name of a # Badger::Config object. We look in the hash, or call the object/class # method to find $name (e.g. $hash->{ $name }, $object->$name, or # $class->name()). This is merged with $params. sub configure { my $self = shift; my $name = shift; my $args = @_ && ref($_[0]) eq 'HASH' ? shift : { @_ }; $self->debug("configure($name)\n") if DEBUG; # $NAME pkg var can be a module name or hash ref with 'module' item my $pkgvar = $self->class->any_var(uc $name); my $pkgmod = ref $pkgvar eq 'HASH' ? $pkgvar->{ module } : $pkgvar; my $config = $self->{ config }; my $method; if ($config && ref $config eq 'HASH') { # $self->{ config } can be a hash ref with a $name item $config = $config->{ $name }; } elsif ($config && ($method = UNIVERSAL::can($self->{ config }, $name))) { # $self->{ config } can be an object with a $name method which we call $config = $method->($config); } else { # no local config data so we'll fall back on a package variable $config = $pkgvar; } # if $config isn't a hash then it's the name of the module to use $config = { module => $config } unless ref $config eq 'HASH'; $self->debug("$name module config: ", $self->dump_data($config)) if DEBUG; # see if a module name is specified in $args, config hash or use $pkgmod my $module = $args->{ module } ||= $config->{ module } ||= $pkgmod || return $self->error_msg( no_module => $name ); $self->debug("$name module: $module") if DEBUG; # load the module class($module)->load; # add any extra arguments to the config hash $config = { %$config, %$args } if %$args; $self->debug("$name merged config: ", $self->dump_data($config)) if DEBUG; return $module->new($config); } #------------------------------------------------------------------------ # destroy() # # Destroy the hub and cleanup any cache items we may have stored. #------------------------------------------------------------------------ sub destroy { my $self = shift; # if called as a class method we cleanup any prototype object # stored as a singleton in the $PROTOTYPE package variable unless (ref $self) { no strict 'refs'; my $class = $self; $self = ${"$class\::PROTOTYPE"} || return; $self->debug("deleting hub prototype from \$$class\::PROTOTYPE\n") if $DEBUG; ${"$class\::PROTOTYPE"} = undef; } $self->debug("destroying hub: $self\n") if $DEBUG; # empty content of $self to break any circular references that # we may have established with other items that point back to us %$self = (); } sub DESTROY { my $self = shift; $self->destroy(); } 1; __END__
# Local Variables: # mode: perl # perl-indent-level: 4 # indent-tabs-mode: nil # End: # # vim: expandtab shiftwidth=4: