# perldoc > Template::Plugin

---
type: CommandReference
command: Template::Plugin
mode: perldoc
section: 
source: perldoc
---

## Quick Reference

- `package MyPlugin; use base qw(Template::Plugin);` — define a new plugin module
- `sub new { my ($class, $context, @params) = @_; ... }` — implement constructor called by `USE`
- `sub load { my ($class, $context) = @_; return $class; }` — optional package method to customise loading
- `return $class->error('No data source') unless $dsn;` — report an error and return undef
- `$object->error()` — retrieve the last error message
- `use Template; my $t = Template->new({ PLUGIN_BASE => 'MyOrg::Template::Plugin' });` — specify custom plugin namespace

## Name

Base class for Template Toolkit plugins

## Synopsis

perl
package MyOrg::Template::Plugin::MyPlugin;
use base qw( Template::Plugin );
use Template::Plugin;
use MyModule;

sub new {
    my $class   = shift;
    my $context = shift;
    bless { ... }, $class;
}
## Options (Methods)

- `load($context)` — Called as package method when plugin is first loaded. Default returns class name. Can return a blessed object for singleton/stateful plugins.
- `new($context, @params)` — Called to instantiate a new plugin object for `USE`. Receives context and any extra parameters. Should return a blessed object.
- `error($error)` — Inherited from `Template::Base`. When called with an argument, sets the error and returns `undef`. When called without, returns the current error. Works as package or object method.

## Examples

### Basic plugin definition

perl
package MyPlugin;
use base qw( Template::Plugin );

sub new {
    my ($class, $context, $dsn) = @_;
    return $class->error('No data source specified') unless $dsn;
    bless { _DSN => $dsn }, $class;
}
### Singleton plugin (load returns blessed object)

perl
package YourPlugin;
sub load {
    my ($class, $context) = @_;
    bless { _CONTEXT => $context }, $class;
}
sub new {
    my ($self, $context, @params) = @_;
    return $self;   # same object every time
}
### Shared server/client pattern

perl
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(@_) }
## See Also

- [Template](https://www.chedong.com/phpMan.php/perldoc/Template/markdown)
- [Template::Plugins](https://www.chedong.com/phpMan.php/perldoc/Template%3A%3APlugins/markdown)
- [Template::Context](https://www.chedong.com/phpMan.php/perldoc/Template%3A%3AContext/markdown)