Search code examples
perldancer

Perl Dancer index.cgi for all requests


I am trying to use the Perl Dancer module in my first application. The first application created a file called MyWeb-App/bin/app.pl which contains this code:

use Dancer;
use MyWeb::App;
dance;

and a file called MyWeb-App/lib/MyWeb/App.pm contains this code:

package MyWeb::App;
use Dancer ':syntax';

our $VERSION = '0.1';

get '/' => sub {
    template 'index';
};

true;

I want one index.cgi file only to serve all my application requests. My question is, do I have to put all my actions/methods in the same MyWeb-App/bin/app.pl file and a module for each action/method like MyWeb-App/lib/MyWeb/App.pm module.

The reason is my application will contains hundreds of actions like this:

get 'register' => sub {...};
post 'save_register' => sub {...};
get 'contactus' => sub {...};
post 'save_contactus' => sub {...};
.....
get 'order' => sub {...};
post 'process_order' => sub {...};

So do I have to put all actions like that in one main index.cgi and I have to modify this file every time I add a new action or new module for the application.

In short, how to make application with large number of actions in modular way so each action in one module file for easy maintenance though other developers could add a separate modules to the application without overlapping/corrupting the main index.cgi.

In my regular none Framework application, I only load modules based on the route/action, so I load only one module per route per action with a simple logic like this:

if ($route eq "register") { eval "use register.pm"; register(); }

elsif ($route eq "save_register") { eval "use register.pm"; save_register(); }
....
....
elsif ($route eq "contactus") { eval "use contactus.pm"; contactus(); }

Solution

  • 'index.cgi' is not used in Perl Dancer.

    The framework intends for you to break up your application into a bunch of logical modules. Group them in a way that makes sense. For example, for a forum application with photos, you might have a "Users" module, a "Messages" module, and a "Photos" module.

    In app.pl, you would have:

     use Dancer;
     use MyWeb::Users;
     use MyWeb::Messages;
     use MyWeb::Photos;
     dance;
    

    You would then create 3 different .pm files within ./lib, say users.pm, messages,pm, photos.pm, etc., and then include the relevant routes for each module. Your routes might begin with /user/, /message/, and /photo/*. For example, POST /user, GET /user, etc. Consider using the prefix function.

    This should keep your project manageable, and your routes organized. As your project grows and you add more modules, you just modify app.pl and to include the new module (and routes).