The Template::Context object that handles the loading and use of
plugins calls the new() and error() methods against the package name
returned by the load() method. In pseudo-code terms, it might look
something like this:
$class = MyPlugin->load($context); # returns 'MyPlugin'
$object = $class->new($context, @params) # MyPlugin->new(...)
|| die $class->error(); # MyPlugin->error()
The load() method may alterately return a blessed reference to an
object instance. In this case, new() and error() are then called as
object methods against that prototype instance.
package YourPlugin;
sub load {
my ($class, $context) = @_;
bless {
_CONTEXT => $context,
}, $class;
}
sub new {
my ($self, $context, @params) = @_;
return $self;
}
In this example, we have implemented a 'Singleton' plugin. One object
gets created when load() is called and this simply returns itself for
each call to new().
Another implementation might require individual objects to be created
for every call to new(), but with each object sharing a reference to
some other object to maintain cached data, database handles, etc.
This pseudo-code example demonstrates the principle.
package MyServer;
sub load {
my ($class, $context) = @_;
bless {
_CONTEXT => $context,
_CACHE => { },
}, $class;
}
sub new {
my ($self, $context, @params) = @_;
MyClient->new($self, @params);
}
sub add_to_cache { ... }
sub get_from_cache { ... }
package MyClient;
sub new {
my ($class, $server, $blah) = @_;
bless {
_SERVER => $server,
_BLAH => $blah,
}, $class;
}
sub get {
my $self = shift;
$self->{ _SERVER }->get_from_cache(@_);
}
sub put {
my $self = shift;
$self->{ _SERVER }->add_to_cache(@_);
}
When the plugin is loaded, a MyServer instance is created. The new()
method is called against this object which instantiates and returns a
MyClient object, primed to communicate with the creating MyServer.
|