The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Dancer2::Plugin - base class for Dancer2 plugins

VERSION

version 0.200001

SYNOPSIS

The plugin itself:

    package Dancer2::Plugin::Polite;

    use strict;
    use warnings;

    use Dancer2::Plugin;

    has smiley => (
        is => 'ro',
        default => sub {
            $_[0]->config->{smiley} || ':-)'
        }
    );

    plugin_keywords 'add_smileys';

    sub BUILD {
        my $plugin = shift;

        $plugin->app->add_hook( Dancer2::Core::Hook->new(
            name => 'after',
            code => sub { $_[0]->content( $_[0]->content . " ... please?" ) }
        ));

        $plugin->app->add_route(
            method => 'get',
            regexp => '/goodbye',
            code   => sub {
                my $app = shift;
                'farewell, ' . $app->request->params->{name};
            },
        );

    }

    sub add_smileys {
        my( $plugin, $text ) = @_;

        $text =~ s/ (?<= \. ) / $plugin->smiley /xeg;

        return $text;
    }

    1;

then to load into the app:

    package MyApp;

    use strict;
    use warnings;

    use Dancer2;

    BEGIN { # would usually be in config.yml
        set plugins => {
            Polite => {
                smiley => '8-D',
            },
        };
    }

    use Dancer2::Plugin::Polite;

    get '/' => sub {
        add_smileys( 'make me a sandwich.' );
    };

    1;

DESCRIPTION

This is an alternate plugin basis for Dancer2.

Writing the plugin

use Dancer2::Plugin

The plugin must begin with

    use Dancer2::Plugin;

which will turn the package into a Moo class that inherits from Dancer2::Plugin. The base class provides the plugin with two attributes: app, which is populated with the Dancer2 app object for which the plugin is being initialized for, and config which holds the plugin section of the application configuration.

Modifying the app at building time

If the plugin needs to tinker with the application -- add routes or hooks, for example -- it can do so within its BUILD() function.

    sub BUILD {
        my $plugin = shift;

        $plugin->app->add_route( ... );
    }

Adding keywords

Via plugin_keywords

Keywords that the plugin wishes to export to the Dancer2 app can be defined via the plugin_keywords keyword:

    plugin_keywords qw/
        add_smileys
        add_sad_kitten
    /;

Each of the keyword will resolve to the class method of the same name. When invoked as keyword, it'll be passed the plugin object as its first argument.

    sub add_smileys {
        my( $plugin, $text ) = @_;

        return join ' ', $text, $plugin->smiley;
    }

    # and then in the app

    get '/' => sub {
        add_smileys( "Hi there!" );
    };

You can also pass the functions directly to plugin_keywords.

    plugin_keywords
        add_smileys => sub {
            my( $plugin, $text ) = @_;

            $text =~ s/ (?<= \. ) / $plugin->smiley /xeg;

            return $text;
        },
        add_sad_kitten => sub { ... };

Or a mix of both styles. We're easy that way:

    plugin_keywords
        add_smileys => sub {
            my( $plugin, $text ) = @_;

            $text =~ s/ (?<= \. ) / $plugin->smiley /xeg;

            return $text;
        },
        'add_sad_kitten';

    sub add_sad_kitten {
        ...;
    }

If you want several keywords to be synonyms calling the same function, you can list them in an arrayref. The first function of the list is taken to be the "real" method to link to the keywords.

    plugin_keywords [qw/ add_smileys add_happy_face /];

    sub add_smileys { ... }

Calls to plugin_keywords are cumulative.

Via the :PluginKeyword function attribute

Keywords can also be defined by adding the :PluginKeyword attribute to the function you wish to export.

    sub foo :PluginKeyword { ... }

    sub bar :PluginKeyword( baz quux ) { ... }

    # equivalent to

    sub foo { ... }
    sub bar { ... }

    plugin_keywords 'foo', [ qw/ baz quux / ] => \&bar;

For an attribute

You can also turn an attribute of the plugin into a keyword.

    has foo => (
        is => 'ro',
        plugin_keyword => 1,  # keyword will be 'foo'
    );

    has bar => (
        is => 'ro',
        plugin_keyword => 'quux',  # keyword will be 'quux'
    );

    has baz => (
        is => 'ro',
        plugin_keyword => [ 'baz', 'bazz' ],  # keywords will be 'baz' and 'bazz'
    );

Accessing the plugin configuration

The plugin configuration is available via the config() method.

    sub BUILD {
        my $plugin = shift;

        if ( $plugin->config->{feeling_polite} ) {
            $plugin->app->add_hook( Dancer2::Core::Hook->new(
                name => 'after',
                code => sub { $_[0]->content( $_[0]->content . " ... please?" ) }
            ));
        }
    }

Getting default values from config file

Since initializing a plugin with either a default or a value passed via the configuration file, like

    has smiley => (
        is => 'ro',
        default => sub {
            $_[0]->config->{smiley} || ':-)'
        }
    );

Dancer2::Plugin allows for a from_config key in the attribute definition. Its value is the plugin configuration key that will be used to initialize the attribute.

If it's given the value 1, the name of the attribute will be taken as the configuration key.

Nested hash keys can also be refered to using a dot notation.

If the plugin configuration has no value for the given key, the attribute default, if specified, will be honored.

If the key is given a coderef as value, it's considered to be a default value combo:

    has foo => (
        is => 'ro',
        from_config => sub { 'my default' },
    );


    # equivalent to
    has foo => (
        is => 'ro',
        from_config => 'foo',
        default => sub { 'my default' },
    );

For example:

    # in config.yml

    plugins:
        Polite:
            smiley: ':-)'
            greeting:
                casual: Hi!
                formal: How do you do?


    # in the plugin

    has smiley => (             # will be ':-)'
        is          => 'ro',
        from_config => 1,
        default     => sub { ':-(' },
    );

    has casual_greeting => (    # will be 'Hi!'
        is          => 'ro',
        from_config => 'greeting.casual',
    );

    has apology => (            # will be 'sorry'
        is          => 'ro',
        from_config => 'apology',
        default     => sub { 'sorry' },
    )

    has closing => (            # will be 'See ya!'
        is => 'ro',
        from_config => sub { 'See ya!' },
    );

Accessing the parent Dancer app

If the plugin is instantiated within a Dancer app, it'll be accessible via the method app().

    sub BUILD {
        my $plugin = shift;

        $plugin->app->add_route( ... );
    }

Using the plugin within the app

A plugin is loaded via

    use Dancer2::Plugin::Polite;

The plugin will assume that it's loading within a Dancer module and will automatically register itself against its app() and export its keywords to the local namespace. If you don't want this to happen, specify that you don't want anything imported via empty parentheses when useing the module:

    use Dancer2::Plugin::Polite ();

Plugins using plugins

This is a (relatively) simple way for a plugin to use another plugin:

    package Dancer2::Plugin::SourPuss;

    has polite => (
        is => 'ro',
        lazy => 1,
        default => sub {
            # if the app already has the 'Polite' plugin loaded, it'll return
            # it. If not, it'll load it in the app, and then return it.
            $_[0]->app->with_plugin( 'Polite' )
        },
        handles => { 'smiley' => 'smiley' },
    );

    sub keywords { qw/ killjoy / }

    sub killjoy {
        my( $plugin, $text ) = @_;

        my $smiley = $plugin->smiley;

        $text =~ s/ $smiley />:-(/xg;

        $text;
    }

Hooks

New plugin hooks are declared via plugin_hooks.

    plugin_hooks 'my_hook', 'my_other_hook';

Hooks are prefixed with plugin.plugin_name. So the plugin my_hook coming from the plugin Dancer2::Plugin::MyPlugin will have the hook name plugin.myplugin.my_hook.

Hooks are executed within the plugin by calling them via the associated app.

    $plugin->execute_plugin_hook( 'my_hook' );

You can also call any other hook if you provide the full name using the execute_hook method:

    $plugin->app->execute_hook( 'core.app.route_exception' );

Or using their alias:

    $plugin->app->execute_hook( 'on_route_exception' );

Writing Test Gotchas

Constructor for Dancer2::Plugin::Foo has been inlined and cannot be updated

You'll usually get this one because you are defining both the plugin and app in your test file, and the runtime creation of Moo's attributes happens after the compile-time import voodoo dance.

To get around this nightmare, wrap your plugin definition in a BEGIN block.

    BEGIN {
        package Dancer2::Plugin::Foo;

        use Dancer2::Plugin;

            has bar => (
                is => 'ro',
                from_config => 1,
            );

            plugin_keywords qw/ bar /;

    }

    {
        package MyApp;

        use Dancer2;
        use Dancer2::Plugin::Foo;

        bar();
    }

You cannot overwrite a locally defined method (bar) with a reader

If you set an object attribute of your plugin to be a keyword as well, you need to call plugin_keywords after the attribute definition.

    package Dancer2::Plugin::Foo;

    use Dancer2::Plugin;

    has bar => (
        is => 'ro',
    );

    plugin_keywords 'bar';

AUTHOR

Dancer Core Developers

COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by Alexis Sukrieh.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.