# NAME

MooX::Role::Pluggable - Add a plugin pipeline to your cows

# SYNOPSIS

    ## A simple pluggable dispatcher.
    package MyDispatcher;
    use Moo;

    use MooX::Role::Pluggable::Constants;

    with 'MooX::Role::Pluggable';

    sub BUILD {
      my ($self) = @_;

      ## (optionally) Configure our plugin pipeline
      $self->_pluggable_init(
        reg_prefix => 'Plug_',
        ev_prefix  => 'Event_',
        types      => {
          NOTIFY  => 'N',
          PROCESS => 'P',
        },
      );
    }

    around '_pluggable_event' => sub {
      ## Override redirecting internal events to process()
      my ($orig, $self) = splice @_, 0, 2;
      $self->process( @_ )
    };

    sub process {
      my ($self, $event, @args) = @_;

    ## Dispatch to 'P_' prefixed "PROCESS" type handlers:
    my $retval = $self->_pluggable_process( 'PROCESS',
      $event,
      \@args
    );

      unless ($retval == EAT_ALL) {
        ## The pipeline allowed the event to continue.
        ## A dispatcher might re-dispatch elsewhere, etc.
      }
    }

    sub shutdown {
      my ($self) = @_;
      ## Unregister all of our plugins.
      $self->_pluggable_destroy;
    }



    ## A Plugin object.
    package MyPlugin;

    use MooX::Role::Pluggable::Constants;

    sub new { bless {}, shift }

    sub Plug_register {
      my ($self, $core) = @_;

    ## Subscribe to events:
    $core->subscribe( $self, 'PROCESS',
      qw/
        my_event
      /,
    );

    ## Log that we're here, do some initialization, etc.

      return EAT_NONE
    }

    sub Plug_unregister {
      my ($self, $core) = @_;
      ## Called at unregister-time.
      return EAT_NONE
    }

    sub P_my_event {
      ## Handle a dispatched "PROCESS"-type event

    my ($self, $core) = splice @_, 0, 2;

    ## Arguments are references and can be modified:
    my $arg = ${ $_[0] };

    . . .

      ## Return an EAT constant to control event lifetime
      ## EAT_NONE allows this event to continue through the pipeline
      return EAT_NONE
    }

    ## An external package that interacts with our dispatcher.
    package MyController;

    use Moo;

    has 'dispatcher' => (
      is      => 'rw',
      default => sub {  MyDispatcher->new()  },
    );

    sub BUILD {
      my ($self) = @_;
      $self->dispatcher->plugin_add( 'MyPlugin',
        MyPlugin->new()
      );
    }

    sub do_stuff {
      my $self = shift;
      $self->dispatcher->process( 'my_event', @_ )
    }

# DESCRIPTION

A [Moo::Role](http://search.cpan.org/perldoc?Moo::Role) for turning instances of your class into pluggable objects.
Consumers of this role gain a plugin pipeline and methods to manipulate it,
as well as a flexible dispatch system (see ["\_pluggable\_process"](#\_pluggable\_process)).

The logic and behavior is based almost entirely on [Object::Pluggable](http://search.cpan.org/perldoc?Object::Pluggable) 
(see ["AUTHOR"](#AUTHOR)). 
Some methods are the same; implementation & interface differ and you 
will still want to read thoroughly if coming from [Object::Pluggable](http://search.cpan.org/perldoc?Object::Pluggable). 
Dispatch is significantly faster -- see ["Performance"](#Performance).

It may be worth noting that this is nothing at all like the Moose 
counterpart [MooseX::Role::Pluggable](http://search.cpan.org/perldoc?MooseX::Role::Pluggable). If the names confuse ... well, I 
lacked for better ideas. ;-)

If you're using [POE](http://search.cpan.org/perldoc?POE), also see [MooX::Role::POE::Emitter](http://search.cpan.org/perldoc?MooX::Role::POE::Emitter).

## Initialization

### \_pluggable\_init

    $self->_pluggable_init(
      ## Prefix for registration events.
      ## Defaults to 'plugin_' ('plugin_register' / 'plugin_unregister')
      reg_prefix   => 'plugin_',

    ## Prefix for dispatched internal events
    ##  (add, del, error, register, unregister ...)
    ## Defaults to 'plugin_ev_'
    event_prefix => 'plugin_ev_',

      ## Map type names to prefixes.
      ## Event types are arbitrary.
      ## Prefix is prepended when dispathing events of a particular type.
      ## Defaults to: { NOTIFY => 'N', PROCESS => 'P' }
      types => {
        NOTIFY  => 'N',
        PROCESS => 'P',
      },
    );

A consumer can call __\_pluggable\_init__ to set up pipeline-related options 
appropriately; this should be done prior to loading plugins or dispatching 
to ["\_pluggable\_process"](#\_pluggable\_process). If it is never called, the defaults 
(as shown above) are used.

__types =>__ can be either an ARRAY of event types (which will be used 
as prefixes):

    types => [ qw/ IncomingEvent OutgoingEvent / ],

... or a HASH mapping an event type to a prefix:

    types => {
      Incoming => 'I',
      Outgoing => 'O',
    },

A '\_' is automatically appended to event type prefixes when events are 
dispatched via ["\_pluggable\_process"](#\_pluggable\_process), but not to 
`reg_prefix`/`event_prefix`.
An empty string `reg_prefix`/`event_prefix` is valid.

### \_pluggable\_destroy

    $self->_pluggable_destroy;

Shuts down the plugin pipeline, unregistering/unloading all known plugins.

### \_pluggable\_event

    ## In our consumer
    sub _pluggable_event {
      my ($self, $event, @args) = @_;
      ## Dispatch out, perhaps.
    }

`_pluggable_event` is called for internal notifications, such as plugin 
load/unload and error reporting (see ["Internal events"](#Internal events)).

It should be overriden in your consuming class to do something useful with 
the dispatched event (and any other arguments passed in).

The `$event` passed will be prefixed with the configured __event\_prefix__.

Also see ["Internal events"](#Internal events)

## Registration

A plugin is any blessed object that is registered with your Pluggable 
object via ["plugin\_add"](#plugin\_add) and usually subscribed to some events via 
["subscribe"](#subscribe).

See ["plugin\_add"](#plugin\_add) regarding loading plugins.

### subscribe

__Subscribe a plugin to some pluggable events.__

    $self->subscribe( $plugin_obj, $type, @events );

Registers a plugin object to receive `@events` of type `$type`.

This is frequently called from within the plugin's registration handler 
(see ["plugin\_register"](#plugin\_register)):

    ## In a plugin:
    sub plugin_register {
      my ($self, $core) = @_;

    $core->subscribe( $self, 'PROCESS',
      qw/
        my_event
        another_event
      /
    );

    $core->subscribe( $self, 'NOTIFY', 'all' );

      EAT_NONE
    }

Subscribe to __all__ to receive all events. It may be worth noting that 
subscribing a lot of plugins to 'all' events will 
cause a performance hit in ["\_pluggable\_process"](#\_pluggable\_process) dispatch versus 
subscribing to specific events.

### unsubscribe

__Unsubscribe a plugin from subscribed events.__

The unregister counterpart to ["subscribe"](#subscribe); stops delivering
specified events to a plugin.

Carries the same arguments as ["subscribe"](#subscribe).

### plugin\_register

__Defined in your plugin(s) and called at load time.__

(Note that 'plugin\_' is just a default register method prefix; it can be 
changed prior to loading plugins. See ["\_pluggable\_init"](#\_pluggable\_init) for details.)

The `plugin_register` method is called on a loaded plugin when it is 
added to the pipeline; it is passed the plugin object (`$self`), the 
Pluggable object, and any arguments given to ["plugin\_add"](#plugin\_add) (or similar 
registration methods).

Normally one might call a ["subscribe"](#subscribe) from here to start receiving 
events after load-time:

    sub plugin_register {
      my ($self, $core, @args) = @_;
      $core->subscribe( $self, 'NOTIFY', @events );
      EAT_NONE
    }

### plugin\_unregister

__Defined in your plugin(s) and called at load time.__

(Note that 'plugin\_' is just a default register method prefix; it can be 
changed prior to loading plugins. See ["\_pluggable\_init"](#\_pluggable\_init) for details.)

The unregister counterpart to ["plugin\_register"](#plugin\_register), called when the object 
is removed from the pipeline (via ["plugin\_del"](#plugin\_del) or 
["\_pluggable\_destroy"](#\_pluggable\_destroy)).

    sub plugin_unregister {
      my ($self, $core) = @_;
      EAT_NONE
    }

Carries the same arguments.

## Dispatch

### \_pluggable\_process

    my $eat = $self->_pluggable_process( $type, $event, \@args );
    return 1 if $eat == EAT_ALL;

The `_pluggable_process` method handles dispatching.

If `$event` is prefixed with our event prefix (see ["\_pluggable\_init"](#\_pluggable\_init)),
the prefix is stripped prior to dispatch (to be replaced with a type 
prefix matching the specified `$type`).

Arguments should be passed in as an ARRAY. During dispatch, references to 
the arguments are passed to subs following automatically-prepended objects 
belonging to the plugin and the pluggable caller, respectively:

    my @args = qw/baz bar/;
    $self->_pluggable_process( 'NOTIFY', 'foo', \@args );

    ## In a plugin:
    sub N_foo {
      my ($self, $core) = splice @_, 0, 2;
      ## Dereferenced expected scalars:
      my $baz = ${ $_[0] };
      my $bar = ${ $_[1] };
    }

This allows for argument modification as an event is passed along the 
pipeline.

Dispatch process for `$event` 'foo' of `$type` 'NOTIFY':

    - Prepend the known prefix for the specified type, and '_'
      'foo' -> 'N_foo'
    - Attempt to dispatch to $self->N_foo()
    - If no such method, attempt to dispatch to $self->_default()
    - If the event was not eaten (see below), dispatch to plugins

"Eaten" means a handler returned a EAT\_\* constant from 
[MooX::Role::Pluggable::Constants](http://search.cpan.org/perldoc?MooX::Role::Pluggable::Constants) indicating that the event's lifetime 
should terminate.

Specifically:

__If our consuming class provides a method or '\_default' that returns:__

    EAT_ALL:    skip plugin pipeline, return EAT_ALL
    EAT_CLIENT: continue to plugin pipeline
                return EAT_ALL if plugin returns EAT_PLUGIN later
    EAT_PLUGIN: skip plugin pipeline entirely
                return EAT_NONE unless EAT_CLIENT was seen previously
    EAT_NONE:   continue to plugin pipeline

__If one of our plugins in the pipeline returns:__

    EAT_ALL:    skip further plugins, return EAT_ALL
    EAT_CLIENT: continue to next plugin, set pending EAT_ALL
                (EAT_ALL will be returned when plugin processing finishes)
    EAT_PLUGIN: return EAT_ALL if previous sub returned EAT_CLIENT
                else return EAT_NONE
    EAT_NONE:   continue to next plugin

This functionality (derived from [Object::Pluggable](http://search.cpan.org/perldoc?Object::Pluggable)) provides 
fine-grained control over event lifetime.

Higher layers can check for an `EAT_ALL` return value from 
\_pluggable\_process to determine whether to continue operating on a 
particular event 
(re-dispatch elsewhere, for example). Plugins can use 'EAT\_CLIENT' to 
indicate that an event should be eaten after plugin processing 
is complete, 'EAT\_PLUGIN' to stop plugin processing, and 'EAT\_ALL' 
to indicate that the event should not be dispatched further.

## Plugin Management Methods

Plugin pipeline manipulation methods will set `$@`, `carp()`, and return 
empty list on error (unless otherwise noted). See ["plugin\_error"](#plugin\_error) 
regarding errors raised during plugin registration and dispatch.

### plugin\_add

    $self->plugin_add( $alias, $plugin_obj, @args );

Add a plugin object to the pipeline. Returns the same values as 
["plugin\_pipe\_push"](#plugin\_pipe\_push).

### plugin\_del

    $self->plugin_del( $alias_or_plugin_obj, @args );

Remove a plugin from the pipeline.

Takes either a plugin alias or object. Returns the removed plugin object.

### plugin\_get

    my $plug_obj = $self->plugin_get( $alias );
	my ($plug_obj, $plug_alias) = $self->plugin_get( $alias_or_plugin_obj );

In scalar context, returns the plugin object belonging to the specified 
alias.

In list context, returns the object and alias, respectively.

### plugin\_alias\_list

    my @loaded = $self->plugin_alias_list;

Returns a list of loaded plugin aliases.

### plugin\_replace

    $self->plugin_replace(
      old    => $alias_or_plugin_obj,
      alias  => $new_alias,
      plugin => $new_plugin_obj,
      ## Optional:
      register_args   => [ ],
      unregister_args => [ ],
    );

Replace an existing plugin object with a new one.

Returns the old (removed) plugin object.

## Pipeline methods

### plugin\_pipe\_push

    $self->plugin_pipe_push( $alias, $plugin_obj, @args );

Add a plugin to the end of the pipeline. (Typically one would use 
["plugin\_add"](#plugin\_add) rather than calling this method directly.)

### plugin\_pipe\_pop

    my $plug = $self->plugin_pipe_pop( @unregister_args );

Pop the last plugin off the pipeline, passing any specified arguments to 
["plugin\_unregister"](#plugin\_unregister).

In scalar context, returns the plugin object that was removed.

In list context, returns the plugin object and alias, respectively.

### plugin\_pipe\_unshift

    $self->plugin_pipe_unshift( $alias, $plugin_obj, @args );

Add a plugin to the beginning of the pipeline.

Returns the total number of loaded plugins (or an empty list on failure).

### plugin\_pipe\_shift

    $self->plugin_pipe_shift( @unregister_args );

Shift the first plugin off the pipeline, passing any specified args to 
["plugin\_unregister"](#plugin\_unregister).

In scalar context, returns the plugin object that was removed.

In list context, returns the plugin object and alias, respectively.

### plugin\_pipe\_get\_index

    my $idx = $self->plugin_pipe_get_index( $alias_or_plugin_obj );
    if ($idx < 0) {
      ## Plugin doesn't exist
    }

Returns the position of the specified plugin in the pipeline.

Returns -1 if the plugin does not exist.

### plugin\_pipe\_insert\_after

    $self->plugin_pipe_insert_after(
      after  => $alias_or_plugin_obj,
      alias  => $new_alias,
      plugin => $new_plugin_obj,
      ## Optional:
      register_args => [ ],
    );

Add a plugin to the pipeline after the specified previously-existing alias 
or plugin object. Returns boolean true on success.

### plugin\_pipe\_insert\_before

    $self->plugin_pipe_insert_before(
      before => $alias_or_plugin_obj,
      alias  => $new_alias,
      plugin => $new_plugin_obj,
      ## Optional:
      register_args => [ ],
    );

Similar to ["plugin\_pipe\_insert\_after"](#plugin\_pipe\_insert\_after), but insert before the specified 
previously-existing plugin, not after.

### plugin\_pipe\_bump\_up

    $self->plugin_pipe_bump_up( $alias_or_plugin_obj, $count );

Move the specified plugin 'up' `$count` positions in the pipeline.

Returns -1 if the plugin cannot be bumped up any farther.

### plugin\_pipe\_bump\_down

    $self->plugin_pipe_bump_down( $alias_or_plugin_obj, $count );

Move the specified plugin 'down' `$count` positions in the pipeline.

Returns -1 if the plugin cannot be bumped down any farther.

## Internal events

These events are dispatched to ["\_pluggable\_event"](#\_pluggable\_event) prefixed with our 
pluggable event prefix; see ["\_pluggable\_init"](#\_pluggable\_init).

### plugin\_error

Issued via ["\_pluggable\_event"](#\_pluggable\_event) when an error occurs.

The arguments are, respectively: the error string, the offending object, 
and a string describing the offending object ('self' or 'plugin' with name 
appended).

### plugin\_added

Issued via ["\_pluggable\_event"](#\_pluggable\_event) when a new plugin is registered.

Arguments are the new plugin alias and object, respectively.

### plugin\_removed

Issued via ["\_pluggable\_event"](#\_pluggable\_event) when a plugin is unregistered.

Arguments are the old plugin alias and object, respectively.

## Performance

Dispatcher performance has been profiled and optimized, but I'm most 
certainly open to ideas ;-)

Some [Benchmark](http://search.cpan.org/perldoc?Benchmark) runs. 30000 ["\_pluggable\_process"](#\_pluggable\_process) calls with 20 loaded 
plugins dispatching one argument to one handler that does nothing except 
return EAT\_NONE:

                        Rate    object-pluggable moox-role-pluggable
    object-pluggable    6173/s                  --                -38%
    moox-role-pluggable 9967/s                 61%

                         Rate    object-pluggable moox-role-pluggable
    object-pluggable     6224/s                  --                -38%
    moox-role-pluggable 10000/s                 61%                  --

                        Rate    object-pluggable moox-role-pluggable
    object-pluggable    6383/s                  --                -35%
    moox-role-pluggable 9868/s                 55%

(Benchmark script is available in the `bench/` directory of the upstream 
repository; see [https://github.com/avenj/moox-role-pluggable](https://github.com/avenj/moox-role-pluggable))

# AUTHOR

Jon Portnoy <avenj@cobaltirc.org>

Written from the ground up, but conceptually based entirely on 
[Object::Pluggable](http://search.cpan.org/perldoc?Object::Pluggable) by BINGOS, HINRIK, APOCAL, japhy et al.
