[dancer-users] A way to separate code into smaller parts/files

Warren Young wyml at etr-usa.com
Thu Apr 23 05:15:58 BST 2015


On Apr 22, 2015, at 6:42 PM, David H <untg99 at gmail.com> wrote:
> 
> What is the best way to separate these code bases into separate files?

Dancer makes this really easy.  The ‘dancer’ generator already created a “lib” directory for you and added it to the module path.  By default, that lib directory only holds myapp.pm, but there’s nothing preventing you from adding more files to that tree.

For my app (which has about 5x the amount of Perl code you’re talking about) I chose to keep lib/myapp.pm as the “Dancer core” module, containing little more than the route handlers.  

Those route handlers are mostly one-liners that call off into one of the other modules which live in lib/myapp/*.pm.

At the top of lib/myapp.pm, you see a bunch of stuff like:

    use myapp::SomeComponent;
    use myapp::AnotherComponent;
    use etc…

Those modules then export classes, functions, and globals in the normal way, for use by the Dancer core module.

Sometimes I write these modules to require fully-qualified names rather than export function to global level.  A route handler thus might look like this:

    prefix '/api' => sub {
        prefix '/sc' => {
            get ‘foo’ => sub {
                return myapp::SomeComponent::GetFoo(param ‘bar’);
            };
        };
    };

If you didn’t know you could nest things with “prefix” this way, aren’t you glad you know now? :)

As you can see, I’m mirroring my Perl module component hierarchy with my URL hierarchy: /api/sc/* is handled by myapp::SomeComponent, etc.


More information about the dancer-users mailing list