Poet::Manual::Intro(3) A gentle introduction to Poet


Poet is a modern Perl web framework for Mason developers. It uses PSGI/Plack for server integration, Mason for request routing and templating, and a selection of best-of-breed CPAN modules for caching, logging and configuration.


If you don't yet have cpanminus ("cpanm"), get it here <http://search.cpan.org/perldoc?App::cpanminus#INSTALLATION>. Then run

    cpanm -S --notest Poet

Omit the ``-S'' if you don't have root, in which case cpanminus will install Poet and prereqs into "~/perl5".

Omit the ``--notest'' if you want to run all the installation tests. Note that this will take about four times as long.


You should now have a "poet" app installed:

    % which poet

Run this to create your initial environment:

    % poet new MyApp
    Now run 'my_app/bin/run.pl' to start your server.

The app name must be a valid Perl class name, generally either "CamelCase" ("MyApp") or an all-uppercase acronym ("TLA"). The directory, if not specified with -d, will be formed from the app name, but lowercased and underscored.


In Poet, your entire web site lives within a single directory hierarchy called the environment. It contains subdirectories for configuration, libraries, Mason components (templates), static files, etc.

Here are the subdirectories that are generated for you. If you don't need some of these directories, feel free to delete them. The only ones really required by Poet are "conf", "comps" and "lib".

  • "bin" - executable scripts
  • "comps" - Mason components (templates)
  • "conf" - configuration files
  • "data" - data not checked into version control, such as cache and object files
  • "db" - database related files such as your schema
  • "lib" - app-specific libraries and Poet subclasses
  • "logs" - logs from web server and from explicit logging statements
  • "static" - static web files - css, images, js
  • "t" - unit tests

Initializing Poet

Any web server or script must initialize Poet before it can use any of Poet's features. This is accomplished by with "Poet::Script":

    use Poet::Script qw($conf $poet);

You'll see this in "bin/run.pl", for example, the script you use to start your webserver. The "use Poet::Script" line does several things:

  • Searches upwards from the script for the environment root (as marked by the ".poet_root" file).
  • Reads and parses your configuration.
  • Unshifts onto @INC the lib/ subdirectory of your environment, so that you can "use" your application modules.
  • Imports the specified quick vars - in this case $conf and $poet - as well as some default utilities into the script namespace. More information about these below.

Relocatable environments

Ideally your environment will be relocatable --- if you move your environment to a different root, or checkout a second copy of it in a different root, things should just work.

To achieve this you should never refer to exact environment directory paths in your code; instead you'll call Poet methods that return them. e.g. instead of this:


you'll do this:


(More information about this $poet variable below.)

App name

Your app name, e.g. "MyApp", is where you are expected to put app-specific subclasses. For example if you have a DBIx::Class schema, you'd create it under "MyApp::Schema" in the file "lib/MyApp/Schema.pm".

The app name is also where Poet will look for subclasses of its own classes.


Poet configuration files are kept in the "conf" subdirectory. The files are in YAML <http://www.yaml.org/> form and are merged in a particular order to create a single configuration hash. (If you want to use something other than YAML you can customize this.)

Configuration files come in three varieties: "global", "layer", and "local", in order from least to highest precedence.

Global configuration applies to all instances of your environment, and is typically checked into version control.

Your generated environment includes a "conf/global.cfg". This is simplest to start out with, but as a site scales in size and number of developers, you can split out your global configuration into multiple files in "conf/global/*.cfg".

Layers allow you to have different configuration for different contexts. With all but the simplest site you'll have at least two layers: development (the internal environment where you develop) and production (the live site). Later on, you might want a staging environment (which looks like production except for a different data source, etc.).

In general you can have as many layers as you like. Each layer has a corresponding configuration file in "conf/layer/*.cfg"; only one layer file will be loaded per environment. We recommend that these files all be checked into version control as well, so that changes to each layer are tracked.

Note: layer is analagous to Plack's environment concept. And in fact, "bin/run.pl" passes the layer to plackup's <-E> option.

"conf/local.cfg" contains configuration local to this specific environment instance. This is where the current layer must be defined. It is also the only configuration file that must exist, and the only one that should not be checked into version control.

You can also specify an extra local file via $ENV{POET_EXTRA_CONF_FILE}.

There are a variety of ways to access configuration:

    my $value = $conf->get('key', 'default');
    my $value = $conf->get_or_die('key');
    my $listref = $conf->get_list('key', ['default']);
    my $hashref = $conf->get_hash('key', {'default' => 5});
    my $bool = $conf->get_boolean('key');

See below for more information about this $conf variable, and see Poet::Conf for more information on specifying and accessing configuration.

Development versus live mode

Although you may have as many layers as you like, Poet also maintains a more limited binary notion of development mode versus live mode. By default, you're in development mode iff layer equals 'development', and in live mode otherwise.

You can use these boolean methods to determine which mode you're in at runtime:


These are mutually exclusive (exactly one is always true).

Poet uses development/live mode to determine things like

  • whether to turn on automatic server restarting
  • whether to display errors in the browser
  • whether to enable debugging utilities

You can customize how mode is determined by subclassing Poet::Conf.


"poet new" generates "bin/run.pl" and "bin/app.psgi" for you.

"bin/run.pl" is a wrapper around plackup, which starts your server. It has a few sensible defaults, such as setting up autorestart in development mode and using an access log in live mode. It will also take a few options from configuration, e.g.

       port: 5000

If you are using something other than plackup (e.g. Server::Starter) then you'll have to adapt this into your own startup script.

"bin/app.psgi" defines your PSGI app. It's the place to add Plack middleware, or change the configuration of the default middleware. For example, to enable basic authentication with an "conf/.htpasswd" file, add this to app.psgi:

    enable "Auth::Htpasswd", file => $poet->conf_path('.htpasswd');


Poet makes it easy to import certain variables (known as ``quick vars'') and utility sets into any module or script in your environment. You've seen two examples of quick vars above: $conf, the global configuration variable, and $poet, the global environment object.

In a script, this looks like:

    use Poet::Script qw($conf :file);

In a module, this looks like:

    package MyApp::Foo;
    use Poet qw($cache $poet);

And every Mason component automatically gets this on top:

    use Poet qw($conf $poet :web);

Debug utilities are automatically imported without having to specify a tag.

See Poet::Import for a complete list of quick vars and utility sets.


HTTP requests are handled with PSGI/Plack and Mason.

A persistent Mason interpreter is created at server startup, with component root set to the "comps" subdirectory. (See Poet::Mason for other default settings and how to configure them.)

When an HTTP request comes in, Poet

  • Constructs a Poet::Plack::Request object from the plack environment. This is a thin subclass of Plack::Request and provides information such as the URL and incoming HTTP headers. It is made available in Mason components as "$m->req".
  • Constructs an empty Poet::Plack::Response object. This is a thin subclass of Plack::Response, and you may use it to set things such as the HTTP status and headers. It is made available in Mason components as "$m->res".
  • Calls "$interp->run" with the URL and the GET/POST parameters. So for example, a URL like


    would result in

        $interp->run("/foo/bar", a=>5, b=>6);

    From there Mason will choose a component to dispatch to - see Mason::Manual::RequestDispatch and Mason::Plugin::RouterSimple.

Generating content with Mason

Mason is a full-featured templating system and beyond our ability to summarize here. Recommended reading:
  • Poet::Manual::Tutorial, especially starting here
  • Mason::Manual::Components
  • Mason::Manual::Syntax

Success and failure results

If the Mason request finishes successfully, the Mason output becomes the plack response body, the status code is set to 200 if it hasn't already been set, and the content type is set to "text/html" (or the specified default content type) if it hasn't already been set.

If the top-level component path cannot be found, the status code is set to 404.

If any other kind of runtime error occurs in development mode, it will be nicely displayed in the browser via StackTrace middleware. Outside of development it will be logged and sent as a 500 error response.

You can call "$m->redirect" and "$m->not_found" to generate redirect and not_found results from a component. These are documented in Poet::Mason.

Multiple values for parameters

If there are multiple values for a GET or POST parameter, generally only the last value will be kept, as per Hash::MultiValue. However, if the corresponding attribute in the page component is declared an "ArrayRef", then all values will be kept and passed in as an arrayref. For example, if the page component "/foo/bar.mc" has these declarations:

    has 'a';
    has 'b' => (isa => "Int");
    has 'c' => (isa => "ArrayRef");
    has 'd' => (isa => "ArrayRef[Int]");

then this URL


would result in

    $interp->run("/foo/bar", a=>2, b=>4, c=>[5,6], d => [7,8]);

You can always get the original Hash::MultiValue object from "$m->request_args". e.g.

    my $hmv = $m->request_args;
    # get all values for 'e'


Poet uses the Log::Log4perl engine for logging, but with a much simpler configuration for the common cases. (If you want to use something other than Log4perl you can customize this.)

Once you have a $log variable, logging looks like:

    $log->error("an error occurred");
    $log->debugf("arguments are: %s", \@_)
        if $log->is_debug();

By default, all logs go to "logs/poet.log" with a reasonable set of metadata such as timestamp.

See Poet::Log for more information.


Poet uses CHI for caching, providing access to a wide variety of cache backends (memory, files, memcached, etc.) You can configure caching differently for different namespaces.

Once you have a $cache variable, caching looks like:

    my $customer = $cache->get($name);
    if ( !defined $customer ) {
        $customer = get_customer_from_db($name);
        $cache->set( $name, $customer, "10 minutes" );


    my $customer2 = $cache->compute($name2, "10 minutes", sub {

By default, everything is cached in files under "data/chi".

See Poet::Cache for more information.


Jonathan Swartz <[email protected]>


This software is copyright (c) 2012 by Jonathan Swartz.

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