Jon Portnoy > MooX-Role-Pluggable-0.120003 > MooX::Role::Pluggable

Download:
MooX-Role-Pluggable-0.120003.tar.gz

Dependencies

Annotate this POD

View/Report Bugs
Module Version: 0.120003   Source   Latest Release: MooX-Role-Pluggable-0.120006

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 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").

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

It may be worth noting that this is nothing at all like the Moose counterpart MooseX::Role::Pluggable. If the names confuse ... well, I lacked for better ideas. ;-)

If you're using POE, also see MooX::Role::POE::Emitter, which consumes this role.

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". 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", 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").

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"

Registration

A plugin is any blessed object that is registered with your Pluggable object via "plugin_add" and usually subscribed to some events via "subscribe".

See "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"):

  ## 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" dispatch versus subscribing to specific events.

unsubscribe

Unsubscribe a plugin from subscribed events.

The unregister counterpart to "subscribe"; stops delivering specified events to a plugin.

Carries the same arguments as "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" 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" (or similar registration methods).

Normally one might call a "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" for details.)

The unregister counterpart to "plugin_register", called when the object is removed from the pipeline (via "plugin_del" or "_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"), 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 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) 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" 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_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" 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".

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".

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", 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" prefixed with our pluggable event prefix; see "_pluggable_init".

plugin_error

Issued via "_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" when a new plugin is registered.

Arguments are the new plugin alias and object, respectively.

plugin_removed

Issued via "_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 runs. 30000 "_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)

AUTHOR ^

Jon Portnoy <avenj@cobaltirc.org>

Written from the ground up, but conceptually based entirely on Object::Pluggable by BINGOS, HINRIK, APOCAL, japhy et al.

syntax highlighting: