http://www.perlmonks.org?node_id=11125631

clemep8 has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to use the same hooks in two Dancer2 apps (I need two apps because of serialization limitations in Dancer2). So, I have the 'hook' calls in a third module. The problem is that the hooks don't seem to get registered in the apps.
package A; use Dancer2 appname => 'A'; use MyHook; ... package B; use Dancer2 appname => 'B'; use MyHook; ... package MyHook; use Dancer2; hook before => sub { print "hello\n"; };
If I append an appname => 'A' to the use Dancer2 directive in MyHook, I can get the hooks registered in app A, and likewise with app B, but I'd like to find a way to get the hooks registered in both apps.

Thoughts?

Replies are listed 'Best First'.
Re: Dancer2 hooks and perl modules
by MrCromeDome (Deacon) on Dec 22, 2020 at 20:37 UTC

    You need to package your module as a plugin to write your own hooks. See Hooks in the Dancer2::Plugin docs for more information.

    More simply, if you just want to add code in the before hook of each app, write the code in a subroutine in a module, use that module in both apps, then call the sub from the before hook of each app.

    Also, if you create a module with the name package A;, use Dancer2; is sufficient. Save yourself a few characters and don't be redundant with use Dancer2 appname =>'A'; And, that's one less thing to maintain if you ever rename that module.

    Cheers!

      Yeah, I can call hook theHook => sub \&theSub; in each app for each hook, but was hoping for something a little more automatic and less redundant...The docs seemed to indicate there was an optional apps property for hook that allowed defining the hook in multiple apps simultaneously, but it doesn't seem to work.
Re: Dancer2 hooks and perl modules
by kcott (Archbishop) on Dec 23, 2020 at 07:11 UTC

    G'day clemep8,

    Welcome to the Monastery.

    Except in a very small number of cases, using single letter identifiers is a very bad idea.

    B is taken and is part of the Perl core, so you'll already have it. See B.

    — Ken