Badger
view release on metacpan or search on metacpan
lib/Badger/Modules.pm view on Meta::CPAN
# This doesn't work yet
use My::Project::Module
preload => 'foo bar baz';
=head2 Example 4 - pre-loading modules and exporting constants (MAYBE)
# Not sure about this.
use My::Project::Module
modules => 'foo bar baz';
my $object = FOO_MODULE->new;
=head1 DESCRIPTION
C<Badger::Modules> is a module for dynamically loading other modules that live
under a common namespace or namespaces.
It is ideally suited for loading plugin extension modules into an application
when you don't know in advance which modules may be required. An example of
such a module is L<Badger::Codecs> which loads L<Badger::Codec> modules for
encoding and decoding data in various formats.
It can also be useful even when you I<do> know what modules you want to use,
or think you do. Delegating the task of loading modules to a central
C<Badger::Modules> object allows you to easily change the modules that are
loaded at a later date, simply by changing the configuration for the
C<Badger::Modules> object.
C<Badger::Modules> can be used as a stand-alone module or as a base class for
creating specialised sub-classes of your own. A subclass of C<Badger::Modules>
can pre-define default values for configuration options. For example, you
might want to create a C<Your::App::Plugins> module that is configured to load
modules under the C<Your::App::Plugin> namespace by default.
Subclasses can also override methods to change the way it works or affect what
happens after a module is loaded. The L<Badger::Factory> module is an example
of such a module. It provides additional methods for dynamically creating
objects and relies on the underlying functionality provided by
C<Badger::Modules> to ensure that the relevant modules are loaded.
=head2 What's the Problem?
Consider the following code fragment showing a subroutine that creates and
uses a C<Your::App::Widget> object.
use Your::App::Widget;
sub some_code {
my $widget = Your::App::Widget->new;
$widget->do_something;
}
One of the benefits of object oriented programming is that objects of
equivalent types are interchangeable. That means that we should be able to
replace the C<Your::App::Widget> object with a different
implementation as long as it has the same interface in terms of the methods it
implements. In strictly typed programming languages this equivalence is
enforced rigidly, by requiring that both objects share a common base class,
expose the same interface, implement a particular role, or some other
mechanism. In loosely typed languages like Perl, we have to rely on duck
typing: if it looks like a duck, floats like a duck and quacks like a duck
then it is a duck (or is close enough to being a duck for practical purposes).
For example, we might want to use a dummy widget object for test purposes.
use Your::App::MockObject::Widget;
sub some_code {
my $widget = Your::App::MockObject::Widget->new;
$widget->do_something;
}
Or perhaps use a C implementation of a module on platforms that support it.
use Your::App::XS::Widget;
sub some_code {
my $widget = Your::App::XS::Widget->new;
$widget->do_something;
}
Or maybe an implementation with additional debugging facilities for use
during development, but not in production code.
use Your::App::Developer::Widget;
sub some_code {
my $widget = Your::App::Developer::Widget->new;
$widget->do_something;
}
By now the problem should be apparent. To use a different implementation of
the widget object we have to go and manually change the code. Every occurrence
of C<Your::App::Widget> in every module of your application must be
changed to the new module name. Of course, if you were doing this in real
life you would probably end up defining a variable to store the name of the
relevant class. Something like this perhaps.
use Your::App::Widget;
our $WIDGET_CLASS = 'Your::App::Widget';
sub some_code {
my $widget = $WIDGET_CLASS->new;
$widget->do_something;
}
This works well in simple cases. However, if you've designed your application
to be suitably modular (thereby promoting reusability of the individual
components and extensibility of the system as a whole) then you may have a
whole bunch of different modules to load, all of which need similar variables.
use Your::App::Widget;
use Your::App::Doodah;
use Your::App::Thingy;
our $WIDGET_CLASS = 'Your::App::Widget';
our $DOODAH_CLASS = 'Your::App::Doodah';
our $THINGY_CLASS = 'Your::App::Thingy';
Not only is the repetition of C<Your::App> in the above code a red
flag for refactoring in itself, but we also have to consider the issue of
sharing these variables among the various modules that might need access to
lib/Badger/Modules.pm view on Meta::CPAN
of namespaces. The C<Badger::Modules> module will try each in turn until
it finds a matching module.
my $modules = Badger::Modules->new(
path => ['My::App','Your::App'],
);
Now when you request the C<Widget> module you'll get
C<My::App::Widget> returned if it exists or
C<Your::App::Widget> if it doesn't.
If neither is available then an error will be thrown as a L<Badger::Exception>
object containing an error message of the format C<module not found: Widget>.
You can set the L<item> configuration option to something other than C<module>
to change this message. For example, setting the C<item> to C<plugin> will
generate a C<plugin not found: Widget> message.
my $modules = Badger::Modules->new(
item => 'plugin',
path => ['My::App::Plugin','Your::App::Plugin'],
);
If you would rather have the L<module()> method return C<undef> to indicate
that a module can't be found then set the C<tolerant> configuration option to
any true value.
my $modules = Badger::Modules->new(
path => ['My::App','Your::App'],
tolerant => 1,
);
It's then up to you to check the return value and handle the case where it is
undefined. The L<error()|Badger::Base/error()> method (inherited from the
L<Badger::Base> base class) can be used to return an error message for the
purposes of friendly error reporting.
my $module = $modules->module('Widget')
|| die $modules->error; # module not found: Widget
Any other errors encountered while loading a module will be reported using
C<croak>, regardless of the L<tolerant> option. These usually indicate syntax
errors requiring immediate attention and thereby warrant the full backtrace
that C<croak> provides.
=head2 Mapping Names
[ROUGH DRAFT]
Name is tried as-is first.
Your::App + Widget = Your::App::Widget
Then we try camel casing it.
Your::App + nice_widget = Your::App::NiceWidget
This allows us to specify names in lower case with underscores separating
words and have them automatically mapped to the correct CamelCase
representation for module names.
Lower case + underscores not only looks nicer (IMHO, YMMV) but can also help
to eliminate problems on filesystems like HFS that are case insensitive by
default. If you're relying on the difference between say, C<CGI> and C<cgi> in
a module name then you're going to have a world of pain the first time you (or
someone else) tries to use that code on a shiny new Mac. And yes, that's me
speaking from personal experience :-)
You may think this is a brain-dead stupid thing to do. You may be right. But
there are brain-dead stupid filesystems out there that we have to accommodate.
=head2 Defining a Badger::Modules Subclass
The C<Badger::Modules> module can be used as a base class for your own
module-loading modules. Here's a complete example.
package My::App::Plugins;
use base 'Badger::Modules';
our $PATH = ['My::App::Plugin', 'Your::App::Plugin'];
1;
The C<$PATH> package variable can be defined to provide the default search
path. The C<$ITEM>, C<$ITEMS>, C<$NAMES> and C<$TOLERANT> package variables
(not shown) can also be used to set the default values for the corresponding
configuration options.
You can then use your subclass like this:
use My::App::Plugins;
my $plugins = My::App::Plugins->new;
my $plugin = $plugins->module('example');
This will load either C<My::App::Plugin::Example> or
C<Your::App::Plugin::Example>, or throw an error to report that the
C<example> module can't be loaded.
You can provide additional configuration options when you create your
subclass object. Any C<path> elements specified will be searched after
those defined in the C<$PATH> package variable.
use My::App::Plugins;
my $plugins = My::App::Plugins->new(
path => 'Our::App::Plugins',
);
my $plugin = $plugins->module('example');
This will load C<My::App::Plugin::Example>, C<Your::App::Plugin::Example>,
C<Our::App::Plugin::Example> or throw an error.
=head2 Using Badger::Modules as a Singleton
You can call the L<module()> method as a class method against
C<Badger::Modules> or any subclass of it.
use My::App::Plugins;
my $plugin = My::App::Plugins->module('example');
In this case the L<module()> method fetches a singleton prototype object
to use (creating it via a call to L<new()>, if necessary). The same prototype
object will be re-used for any subsequent class methods.
=head1 CONFIGURATION OPTIONS
lib/Badger/Modules.pm view on Meta::CPAN
wibble_path => ['My::Modules', 'Your::Modules'],
);
A default value can be provided by a C<$ITEM> package variable in a subclass
of C<Badger::Modules>.
package My::App::Plugins;
use base 'Badger::Modules';
our $ITEM = 'plugin';
1;
Another effect of setting C<item> is that it allows you to specify the
C<path> option using the item name as a prefix.
my $modules = Badger::Modules->new(
item => 'plugin',
plugin_path => ['My::App::Plugin', 'Your::App::Plugin'],
);
This can be useful if you've got several different module loaders in an
application and want to avoid confusion between the different C<path>
configuration options.
=head2 items
This can be used to specify the correct plural form of the L<item> name for
those cases where the singular form does not pluralise regularly (where
"regularly" is defined as something that the
L<plural()|Badger::Utils/plural()> function can handle.
my $modules = Badger::Modules->new(
# highly contrived example
item => 'attorney_general',
items => 'attorneys_general',
);
A default value can be provided by a C<$ITEMS> package variable in a subclass
of C<Badger::Modules>.
package My::App::Plugins;
use base 'Badger::Modules';
our $ITEM = 'attorney_general';
our $ITEMS = 'attorneys_general';
1;
Note that this isn't used in the base class, but some subclasses rely on it
to generate useful error messages.
=head2 names
This can be used to provide an explicit mapping for module names that may
be requested via the L<module()> method. The default behaviour is to
camel case module names that are separated by underscores. For example,
requesting a C<foo_bar> module will look for a C<FooBar> module in any of
the L<path> locations.
This work well enough for most modules, but some do not capitalise
consistently. Modules whose names contain acronyms like C<URL> are typically
prone to a dose of fail.
$module = $modules->module('url'); # looks for XXX::Url not XXX::URL
If you specify the name in the correct capitalisation then you'll have no
problem.
$module = $modules->module('URL');
If like me you prefer to use case-insensitive throughout and leave it up to
the module loader to worry about the correct capitalisation then the C<names>
option is your friend. You can use to define any number of simple aliases
for the L<module()> method to use.
$modules = Badger::Modules->new(
path => ['My::Plugin', 'Your::Plugin'],
names => {
url => 'URL',
cgi => 'CGI',
foo => 'iFoo::XS'
}
);
Note that the values specified in the C<names> hash array are partial module
names. They will still be applied to the base paths specified in the C<path>
option to generate complete candidate module paths.
=head2 tolerant
This option affects what happens when a module requested via the L<module()>
method cannot be found. In the usual case, the tolerant option is not set and
the L<module()> method will throw a "module not found: XXX" error. If the
C<tolerant> option is set then the method will instead return C<undef>
=head1 METHODS
=head2 new()
Constructor method to create a new C<Badger::Modules> object. Inherited from
the L<Badger::Base> base class.
=head2 module($name)
Method to load a module identified by C<$name>.
[ROUGH DRAFT]
* name is aliased via names lookup table
* name is expanded to various possible capitalisations
* each base namespace in path is tried...
* with each name...
* until one is located and loaded, in which case found() is called
(or failed() if an error occurred while loading the module)
* or we exhaust all possibilities, in which case not_found() is called.
=head2 modules()
This method can be used to get or set the internal mapping of names to
( run in 0.531 second using v1.01-cache-2.11-cpan-364913b4093 )