Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Cool uses for Dancer/Mojo hooks

by Dallaylaen (Chaplain)
on Dec 13, 2016 at 17:00 UTC ( #1177718=perlquestion: print w/replies, xml ) Need Help??

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

Hello dear esteemed monks,

After announcing my toy web framework to a local Perl mongers group, I received a request from fellow monger to add filters. He was citing sinatra.rb as reference. I promptly found both Mojolicious and Dancer to have similar functionality called hooks. Apache/mod_perl allows to hook into different stages of request processing as well, and I was planning to do something like that as well.

So I set myself on a quest to add hooks. However, the very first attempts turned out to be utterly over-engineered (almost everything I do is, see Implementing methods in a subclass or providing in-place callback: Is it overengineered?). It's easy to make a mistake, and it would be hard to correct it later.

Some background: the framework goes as follows:

use strict; use warnings; use MVC::Neaf; MVC::Neaf->route( '/some/uri/path' => sub { my $request = shift; # ... query request object for params, cookies, etc # a valid way to return configurable error page die 403 if $perm_denied; # result will be fed to View's render() method # the user-agent will get a 200 page with some headers # and rendered content return \%hash; }, view => 'TT'); # more handlers MVC::Neaf->run; # end of the application (as in PSGI or Dancer)

What I clearly want:

  • Defining hooks in form of pair<path, stage> => sub { my $request = shift; # .... };
  • Hooks for ALL paths prefixing the URI path being executed in order
  • Multiple hooks can be added for the same path (we'll have to stack them anyway)

What I'm unsure about:

  • What the stages are? I see at least pre-route, pre-handler, pre-respond and post-cleanup, but maybe there are more. There's a clear gap between handler and rendering to put a hook as well.
  • How to share state between handlers? It looks like I'll need some per-request data storage.

So before I proceed to answering these questions I would like to ask for example usage of this feature. Here's what I can think of:

  • Authorisation - checking a user is authorized to access certain part of the website (or is logged in at all to begin with).
  • Fetching an entity - if separate GET/POST/PUT/PATCH handlers are set up for the same URI, load what they operate on before proceeding. I don't like the idea, but I can't forbid others to do so.
  • Gathering site response time stats - currently hardwired into the module's core, want to split it out anyway.
  • Cleaning up stuff - Neaf has built-in $request->postpone(sub { ... }); functionality, but maybe this can be generalized.
  • Handling language/country setup - via cookies, geoIP etc.

What else did you encounter / think about doing via such hooks in real-life applications? Thank you.

Replies are listed 'Best First'.
Re: Cool uses for Dancer/Mojo hooks (libraries over frameworks)
by tye (Sage) on Dec 14, 2016 at 05:05 UTC

    Frameworks are a pain, mostly because they end up needing hooks to be implemented. Hooks suck for more reasons that just it not being obvious what hooks should even be provided.

    Libraries are a much better form of abstraction. Implement your functionality in properly abstracted subroutines with clear names that are easy to test. Then, if a user just wants the default behavior, they can just call the top-level subroutine and be done. If they want to customize parts, then they instead copy the structure of the top-level subroutine but add in their custom code where they need to. The top level subroutine should just be calls to other subroutines.

    If you can easily test your subroutines and can give them clear names, then you've abstracted things well which means that the places where customization will be wanted are very likely to be "between" those subroutine calls.

    - tye        

      Thanks for your reply.

      Frameworks are a pain

      If they weren't, I wouldn't even bother to roll my own. And I'm trying hard to make Neaf [ni:f] act like you describe where possible.

      For instance, Neaf's Request is just a regular class that is queried through public methods by both the core and the user's code. Neaf's Session storage is just a regular class with a well known interface (somewhat weird, though). Neaf's View is a regular object* with render method that converts a hashref to a pair of scalars (content & content-type). And the Model is entirely left up to the user and is supposed to be a normal Perl library usable from a standalone script.

      That said, there are two complications:

      1. Being run from under a web server imposes at least one inversion of control (i.e. need for hook) no matter what we do. Splitting the app into routes via URI path looks natural here. Returning status looks natural, so I decided to take it as far as "return a plain hash for rendering or die with a numeric code". But anyway the IoC is already there. Special measures are taken so that a Neaf application can run as a command-line script with --help and --list switches to aid debugging.

      2. From my experience, top-down applications somehow tend to mix logic and side effects, eventually growing into huge monoliths tied to the web-server in use. The neat code glue between the well-defined, self-documenting function calls grows longer, and nobody ever cares to refactor it into more functions. It all ends in a huge Jack-of-all-trades function that has half of the model in it and cannot be split into smaller ones. Which of course is no worse than a callback hell ridden with cryptic side effects.

      So now I'm seeking help in order to construct the shortest, the most obvious hook sequence with simple, straightforward primitives for transmitting shared state. Unfortunately, my own experience with existing frameworks is not enough to make conclusions. And my experience with AnyEvent tells me to be very careful when it comes to making room for callbacks.


      * view => 'TT' mentioned in the example is actually a predefined alias to MVC::Neaf::View::TT->new(). One can create more such aliases via MVC::Neaf->load_view() function.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1177718]
Approved by herveus
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2020-10-31 02:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (286 votes). Check out past polls.

    Notices?