.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Dancer::Cookbook 3pm" .TH Dancer::Cookbook 3pm "2023-02-10" "perl v5.36.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Dancer::Cookbook \- a quick\-start guide to the Dancer web framework .SH "VERSION" .IX Header "VERSION" version 1.3521 .SH "DESCRIPTION" .IX Header "DESCRIPTION" A quick-start guide with examples to get you up and running with the Dancer web framework. .SH "BEGINNER'S DANCE" .IX Header "BEGINNER'S DANCE" .SS "Your first Dancer web app" .IX Subsection "Your first Dancer web app" Dancer has been designed to be easy to work with. It's trivial to write a simple web app, but still has the power to work with larger projects. To start with, let's make an incredibly simple \*(L"Hello World\*(R" example: .PP .Vb 1 \& #!/usr/bin/perl \& \& use Dancer; \& \& get \*(Aq/hello/:name\*(Aq => sub { \& return "Why, hello there " . params\->{name}; \& }; \& \& dance; .Ve .PP Yes, the above is a fully-functioning web app; running that script will launch a webserver listening on the default port (3000). Now you can make a request .PP .Vb 2 \& $ curl http://localhost:3000/hello/Bob \& Why, hello there Bob .Ve .PP (or the name of the machine you ran it on, if it's not your local system), and it will say hello. The \f(CW\*(C`:name\*(C'\fR part is a named parameter within the route specification whose value is made available through \f(CW\*(C`params\*(C'\fR \&\- more on that later. .PP Note that you don't need to use the \f(CW\*(C`strict\*(C'\fR and \f(CW\*(C`warnings\*(C'\fR pragma, they are already loaded by Dancer. (If you don't want the \f(CW\*(C`warnings\*(C'\fR pragma (which can lead to undesired warnings about use of undef values, for example), then set the import_warnings setting to a false value. .SS "Starting a Dancer project" .IX Subsection "Starting a Dancer project" The first simple example is fine for trivial projects, but for anything more complex you'll want a more maintainable solution \- enter the \f(CW\*(C`dancer\*(C'\fR helper script, which will build the framework of your application with a single command: .PP .Vb 10 \& $ dancer \-a mywebapp \& + mywebapp \& + mywebapp/bin \& + mywebapp/bin/app.pl \& + mywebapp/config.yml \& + mywebapp/environments \& + mywebapp/environments/development.yml \& + mywebapp/environments/production.yml \& + mywebapp/views \& + mywebapp/views/index.tt \& + mywebapp/views/layouts \& + mywebapp/views/layouts/main.tt \& + mywebapp/MANIFEST.SKIP \& + mywebapp/lib \& + mywebapp/lib/mywebapp.pm \& + mywebapp/public \& + mywebapp/public/css \& + mywebapp/public/css/style.css \& + mywebapp/public/css/error.css \& + mywebapp/public/images \& + mywebapp/public/500.html \& + mywebapp/public/404.html \& + mywebapp/public/dispatch.fcgi \& + mywebapp/public/dispatch.cgi \& + mywebapp/public/javascripts \& + mywebapp/public/javascripts/jquery.min.js \& + mywebapp/t \& + mywebapp/t/002_index_route.t \& + mywebapp/t/001_base.t \& + mywebapp/Makefile.PL .Ve .PP As you can see, it creates a directory named after the name of the app, along with a configuration file, a views directory (where your templates and layouts will live), an environments directory (where environment-specific settings live), a module containing the actual guts of your application, a script to start it \- or to run your web app via Plack/PSGI \- more on that later. .SH "DANCE ROUTINES: ROUTES" .IX Header "DANCE ROUTINES: ROUTES" .SS "Declaring routes" .IX Subsection "Declaring routes" To control what happens when a web request is received by your webapp, you'll need to declare \f(CW\*(C`routes\*(C'\fR. A route declaration indicates for which \s-1HTTP\s0 method(s) it is valid, the path it matches (e.g. /foo/bar), and a coderef to execute, which returns the response. .PP .Vb 3 \& get \*(Aq/hello/:name\*(Aq => sub { \& return "Hi there " . params\->{name}; \& }; .Ve .PP The above route specifies that, for \s-1GET\s0 requests to '/hello/...', the code block provided should be executed. .SS "Handling multiple \s-1HTTP\s0 request methods" .IX Subsection "Handling multiple HTTP request methods" Routes can use \f(CW\*(C`any\*(C'\fR to match all, or a specified list of \s-1HTTP\s0 methods. .PP The following will match any \s-1HTTP\s0 request to the path /myaction: .PP .Vb 3 \& any \*(Aq/myaction\*(Aq => sub { \& # code \& } .Ve .PP The following will match \s-1GET\s0 or \s-1POST\s0 requests to /myaction: .PP .Vb 3 \& any [\*(Aqget\*(Aq, \*(Aqpost\*(Aq] => \*(Aq/myaction\*(Aq => sub { \& # code \& }; .Ve .PP For convenience, any route which matches \s-1GET\s0 requests will also match \s-1HEAD\s0 requests. .SS "Retrieving request parameters" .IX Subsection "Retrieving request parameters" The params keyword returns a hashref of request parameters; these will be parameters supplied on the query string, within the path itself (with named placeholders), and, for \s-1HTTP POST\s0 requests, the content of the \&\s-1POST\s0 body. .SS "Named parameters in route path declarations" .IX Subsection "Named parameters in route path declarations" As seen above, you can use \f(CW\*(C`:somename\*(C'\fR in a route's path to capture part of the path; this will become available by calling params. .PP So, for a web app where you want to display information on a company, you might use something like: .PP .Vb 4 \& get \*(Aq/company/view/:companyid\*(Aq => sub { \& my $company_id = params\->{companyid}; \& # Look up the company and return appropriate page \& }; .Ve .SS "Wildcard path matching and splat" .IX Subsection "Wildcard path matching and splat" You can also declare wildcards in a path, and retrieve the values they matched with the splat keyword: .PP .Vb 11 \& get \*(Aq/*/*\*(Aq => sub { \& my ($action, $id) = splat; \& if (my $action eq \*(Aqview\*(Aq) { \& return display_item($id); \& } elsif ($action eq \*(Aqdelete\*(Aq) { \& return delete_item($id); \& } else { \& status \*(Aqnot_found\*(Aq; \& return "What?"; \& } \& }; .Ve .SS "Before hooks \- processed before a request" .IX Subsection "Before hooks - processed before a request" A before hook declares code which should be handled before a request is passed to the appropriate route. .PP .Vb 4 \& hook \*(Aqbefore\*(Aq => sub { \& var note => \*(AqHi there\*(Aq; \& request\->path_info(\*(Aq/foo/oversee\*(Aq) \& }; \& \& get \*(Aq/foo/*\*(Aq => sub { \& my ($match) = splat; # \*(Aqoversee\*(Aq; \& vars\->{note}; # \*(AqHi there\*(Aq \& }; .Ve .PP The above declares a before hook which uses \f(CW\*(C`var\*(C'\fR to set a variable which will later be available within the route handler, then amends the path of the request to \f(CW\*(C`/foo/oversee\*(C'\fR; this means that, whatever path was requested, it will be treated as though the path requested was \f(CW\*(C`/foo/oversee\*(C'\fR. .SS "Default route" .IX Subsection "Default route" In case you want to avoid a \fI404 error\fR, or handle multiple routes in the same way and you don't feel like configuring all of them, you can set up a default route handler. .PP The default route handler will handle any request that doesn't get served by any other route. .PP All you need to do is set up the following route as the \fBlast\fR route: .PP .Vb 4 \& any qr{.*} => sub { \& status \*(Aqnot_found\*(Aq; \& template \*(Aqspecial_404\*(Aq, { path => request\->path }; \& }; .Ve .PP Then you can set up the template as such: .PP .Vb 1 \& You tried to reach <% path %>, but it is unavailable at the moment. \& \& Please try again or contact us at our email at <...>. .Ve .SS "Using the auto_page feature for automatic route creation" .IX Subsection "Using the auto_page feature for automatic route creation" For simple \*(L"static\*(R" pages, you can simply enable the \f(CW\*(C`auto_page\*(C'\fR config setting; this means that you need not declare a route handler for those pages; if a request is for \f(CW\*(C`/foo/bar\*(C'\fR, Dancer will check for a matching view (e.g. \&\f(CW\*(C`/foo/bar.tt\*(C'\fR and render it with the default layout etc if found. For full details, see the documentation for the auto_page setting. .SS "Why should I use the Ajax plugin" .IX Subsection "Why should I use the Ajax plugin" As an Ajax query is just an \s-1HTTP\s0 query, it's similar to a \s-1GET\s0 or \s-1POST\s0 route. You may ask yourself why you may want to use the \f(CW\*(C`ajax\*(C'\fR keyword (from the Dancer::Plugin::Ajax plugin) instead of a simple \&\f(CW\*(C`get\*(C'\fR. .PP Let's say you have a path like '/user/:user' in your application. You may want to be able to serve this page, with a layout and \s-1HTML\s0 content. But you may also want to be able to call this same url from a javascript query using Ajax. .PP So, instead of having the following code: .PP .Vb 10 \& get \*(Aq/user/:user\*(Aq => sub { \& if (request\->is_ajax) { \& # create xml, set headers to text/xml, blablabla \& header(\*(AqContent\-Type\*(Aq => \*(Aqtext/xml\*(Aq); \& header(\*(AqCache\-Control\*(Aq => \*(Aqno\-store, no\-cache, must\-revalidate\*(Aq); \& to_xml({...}) \& }else{ \& template users, {....} \& } \& }; .Ve .PP you can have .PP .Vb 3 \& get \*(Aq/user/:user\*(Aq => sub { \& template users, {...} \& } .Ve .PP and .PP .Vb 3 \& ajax \*(Aq/user/:user\*(Aq => sub { \& to_xml({...}, RootName => undef); \& } .Ve .PP Because it's an Ajax query you know you need to return \s-1XML\s0 content, so the content type of the response is set for you. .SS "Using the prefix feature to split your application" .IX Subsection "Using the prefix feature to split your application" For better maintainability you may want to separate some of your application components to different packages. Let's say we have a simple web app with an admin section, and want to maintain this in a different package: .PP .Vb 3 \& package myapp; \& use Dancer \*(Aq:syntax\*(Aq; \& use myapp::admin; \& \& prefix undef; \& \& get \*(Aq/\*(Aq => sub {...}; \& \& 1; \& \& package myapp::admin; \& use Dancer \*(Aq:syntax\*(Aq; \& \& prefix \*(Aq/admin\*(Aq; \& \& get \*(Aq/\*(Aq => sub {...}; \& \& 1; .Ve .PP The following routes will be generated for us: .PP .Vb 4 \& \- get / \& \- get /admin/ \& \- head / \& \- head /admin/ .Ve .SH "MUSCLE MEMORY: STORING DATA" .IX Header "MUSCLE MEMORY: STORING DATA" .SS "Handling sessions" .IX Subsection "Handling sessions" It's common to want to use sessions to give your web applications state; for instance, allowing a user to log in, creating a session, and checking that session on subsequent requests. .PP To make use of sessions you must first enable the session engine. Pick the session engine you want to use, then declare it in your config file: .PP .Vb 1 \& session: Simple .Ve .PP The Dancer::Session::Simple backend implements very simple in-memory session storage. This will be fast and useful for testing, but sessions do not persist between restarts of your app. .PP You can also use the Dancer::Session::YAML backend included with Dancer, which stores session data on disc in \s-1YAML\s0 files (since \s-1YAML\s0 is a nice human-readable format, it makes inspecting the contents of sessions a breeze): .PP .Vb 1 \& session: YAML .Ve .PP Or, to enable session support from within your code, .PP .Vb 1 \& set session => \*(AqYAML\*(Aq; .Ve .PP (Controlling settings is best done from your config file, though). '\s-1YAML\s0' in the example is the session backend to use; this is shorthand for Dancer::Session::YAML. There are other session backends you may wish to use, for instance Dancer::Session::Memcache, but the \s-1YAML\s0 backend is a simple and easy to use example which stores session data in a \s-1YAML\s0 file in sessions). .PP You can then use the session keyword to manipulate the session: .PP \fIStoring data in the session\fR .IX Subsection "Storing data in the session" .PP Storing data in the session is as easy as: .PP .Vb 1 \& session varname => \*(Aqvalue\*(Aq; .Ve .PP \fIRetrieving data from the session\fR .IX Subsection "Retrieving data from the session" .PP Retrieving data from the session is as easy as: .PP .Vb 1 \& session(\*(Aqvarname\*(Aq) .Ve .PP Or, alternatively, .PP .Vb 1 \& session\->{varname} .Ve .PP \fIControlling where sessions are stored\fR .IX Subsection "Controlling where sessions are stored" .PP For disc-based session back ends like Dancer::Session::YAML, Dancer::Session::Storable etc, session files are written to the session dir specified by the \f(CW\*(C`session_dir\*(C'\fR setting, which defaults to \f(CW\*(C`appdir/sessions\*(C'\fR. .PP If you need to control where session files are created, you can do so quickly and easily within your config file. For example: .PP .Vb 1 \& session_dir: /tmp/dancer\-sessions .Ve .PP If the directory you specify does not exist, Dancer will attempt to create it for you. .PP \fIDestroying a session\fR .IX Subsection "Destroying a session" .PP When you're done with your session, you can destroy it: .PP .Vb 1 \& session\->destroy .Ve .SS "Sessions and logging in" .IX Subsection "Sessions and logging in" A common requirement is to check the user is logged in, and, if not, require them to log in before continuing. .PP This can easily be handled with a before hook to check their session: .PP .Vb 6 \& hook \*(Aqbefore\*(Aq => sub { \& if (! session(\*(Aquser\*(Aq) && request\->path_info !~ m{^/login}) { \& var requested_path => request\->path_info; \& request\->path_info(\*(Aq/login\*(Aq); \& } \& }; \& \& get \*(Aq/login\*(Aq => sub { \& # Display a login page; the original URL they requested is available as \& # vars\->{requested_path}, so could be put in a hidden field in the form \& template \*(Aqlogin\*(Aq, { path => vars\->{requested_path} }; \& }; \& \& post \*(Aq/login\*(Aq => sub { \& # Validate the username and password they supplied \& if (params\->{user} eq \*(Aqbob\*(Aq && params\->{pass} eq \*(Aqletmein\*(Aq) { \& session user => params\->{user}; \& redirect params\->{path} || \*(Aq/\*(Aq; \& } else { \& redirect \*(Aq/login?failed=1\*(Aq; \& } \& }; .Ve .PP In your login page template, you'll want a text field named user, a password field named pass, and a hidden field named path, which will be populated with the path originally requested, so that it's sent back in the \s-1POST\s0 submission, and can be used by the post route to redirect onwards to the page originally requested once you're logged in. .PP Of course you'll probably want to validate your users against a database table, or maybe via IMAP/LDAP/SSH/POP3/local system accounts via \s-1PAM\s0 etc. Authen::Simple is probably a good starting point here! .PP A simple working example of handling authentication against a database table yourself (using Dancer::Plugin::Database which provides the \f(CW\*(C`database\*(C'\fR keyword, and Crypt::SaltedHash to handle salted hashed passwords (well, you wouldn't store your users' passwords in the clear, would you?)) follows: .PP .Vb 10 \& post \*(Aq/login\*(Aq => sub { \& my $user = database\->quick_select(\*(Aqusers\*(Aq, \& { username => params\->{user} } \& ); \& if (!$user) { \& warning "Failed login for unrecognised user " . params\->{user}; \& redirect \*(Aq/login?failed=1\*(Aq; \& } else { \& if (Crypt::SaltedHash\->validate($user\->{password}, params\->{pass})) \& { \& debug "Password correct"; \& # Logged in successfully \& session user => $user; \& redirect params\->{path} || \*(Aq/\*(Aq; \& } else { \& debug("Login failed \- password incorrect for " . params\->{user}); \& redirect \*(Aq/login?failed=1\*(Aq; \& } \& } \& }; .Ve .PP \fIRetrieve complete hash stored in session\fR .IX Subsection "Retrieve complete hash stored in session" .PP Get complete hash stored in session: .PP .Vb 1 \& my $hash = session; .Ve .SH "APPEARANCE" .IX Header "APPEARANCE" .SS "Using templates \- views and layouts" .IX Subsection "Using templates - views and layouts" Returning plain content is all well and good for examples or trivial apps, but soon you'll want to use templates to maintain separation between your code and your content. Dancer makes this easy. .PP Your route handlers can use the template keyword to render templates. .PP \fIViews\fR .IX Subsection "Views" .PP It's possible to render the action's content with a template, this is called a view. The `appdir/views' directory is the place where views are located. .PP You can change this location by changing the setting 'views'. .PP By default, the internal template engine Dancer::Template::Simple is used, but you may want to upgrade to Template::Toolkit. If you do so, you have to enable this engine in your settings as explained in Dancer::Template::TemplateToolkit. If you do so, you'll also have to import the Template module in your application code. .PP Note that, by default, Dancer configures the Template::Toolkit engine to use \&\f(CW\*(C`<% %\*(C'\fR> brackets instead of its default \f(CW\*(C`[% %]\*(C'\fR brackets. You can change this by using the following in your config file: .PP .Vb 1 \& template: template_toolkit \& \& engines: \& template_toolkit: \& start_tag: \*(Aq[%\*(Aq \& stop_tag: \*(Aq%]\*(Aq .Ve .PP All views must have a '.tt' extension. This may change in the future. .PP To render a view just call the \f(CW\*(C`template|Dancer/template\*(C'\fR keyword at the end of the action by giving the view name and the \s-1HASHREF\s0 of tokens to interpolate in the view (note that for convenience, the request, session, params and vars are automatically accessible in the view, named \f(CW\*(C`request\*(C'\fR, \f(CW\*(C`session\*(C'\fR, \&\f(CW\*(C`params\*(C'\fR and \f(CW\*(C`vars\*(C'\fR). For example: .PP .Vb 1 \& hook \*(Aqbefore\*(Aq => sub { var time => scalar(localtime) }; \& \& get \*(Aq/hello/:name\*(Aq => sub { \& my $name = params\->{name}; \& template \*(Aqhello.tt\*(Aq, { name => $name }; \& }; .Ve .PP The template 'hello.tt' could contain, for example: .PP .Vb 6 \&

Hi there, <% name %>!

\&

You\*(Aqre using <% request.user_agent %>

\& <% IF session.username %> \&

You\*(Aqre logged in as <% session.username %> \& <% END %> \& It\*(Aqs currently <% vars.time %> .Ve .PP For a full list of the tokens automatically added to your template (like \f(CW\*(C`session\*(C'\fR, \f(CW\*(C`request\*(C'\fR and \f(CW\*(C`vars\*(C'\fR, refer to Dancer::Template::Abstract). .PP \fILayouts\fR .IX Subsection "Layouts" .PP A layout is a special view, located in the 'layouts' directory (inside the views directory) which must have a token named 'content'. That token marks the place to render the action view. This lets you define a global layout for your actions, and have each individual view contain only the specific content. This is a good thing to avoid lots of needless duplication of \s-1HTML :\s0) .PP Here is an example of a layout: \f(CW\*(C`views/layouts/main.tt\*(C'\fR : .PP .Vb 6 \& \& ... \& \&

\& \&
\& <% content %> \&
\& \& \& .Ve .PP You can tell your app which layout to use with \f(CW\*(C`layout: name\*(C'\fR in the config file, or within your code: .PP .Vb 1 \& set layout => \*(Aqmain\*(Aq; .Ve .PP You can control which layout to use (or whether to use a layout at all) for a specific request without altering the layout setting by passing an options hashref as the third param to the template keyword: .PP .Vb 1 \& template \*(Aqindex.tt\*(Aq, {}, { layout => undef }; .Ve .PP If your application is not mounted under root (\fB/\fR), you can use a before_template_render hook instead of hardcoding the path to your application for your css, images and javascript: .PP .Vb 4 \& hook \*(Aqbefore_template_render\*(Aq => sub { \& my $tokens = shift; \& $tokens\->{uri_base} = request\->base\->path; \& }; .Ve .PP Then in your layout, modify your css inclusion as follows: .PP .Vb 1 \& .Ve .PP From now on, you can mount your application wherever you want, without any further modification of the css inclusion .PP \fItemplate and unicode\fR .IX Subsection "template and unicode" .PP If you use Plack and have some unicode problem with your Dancer application, don't forget to check if you have set your template engine to use unicode, and set the default charset to \s-1UTF\-8.\s0 So, if you are using template toolkit, your config.yml will look like this: .PP .Vb 4 \& charset: UTF\-8 \& engines: \& template_toolkit: \& ENCODING: utf8 .Ve .PP \fI\s-1TT\s0's \s-1WRAPPER\s0 directive in Dancer (\s-1META\s0 variables, SETs)\fR .IX Subsection "TT's WRAPPER directive in Dancer (META variables, SETs)" .PP Dancer already provides a WRAPPER-like ability, which we call a \*(L"layout\*(R". The reason we do not use \s-1TT\s0's \s-1WRAPPER\s0 (which also makes it incompatible with Dancer) is because not all template systems support it. Actually, most don't. .PP However, you might want to use it, and be able to define \s-1META\s0 variables and regular Template::Toolkit variables. .PP These few steps will get you there: .IP "\(bu" 4 Disable the layout in Dancer .Sp You can do this by simply commenting (or removing) the \f(CW\*(C`layout\*(C'\fR configuration in the \fIconfig.yml\fR file. .IP "\(bu" 4 Use Template Toolkit template engine .Sp Change the configuration of the template to Template Toolkit: .Sp .Vb 2 \& # in config.yml \& template: "template_toolkit" .Ve .IP "\(bu" 4 Tell the Template Toolkit engine who's your wrapper .Sp .Vb 5 \& # in config.yml \& # ... \& engines: \& template_toolkit: \& WRAPPER: layouts/main.tt .Ve .PP Done! Everything will work fine out of the box, including variables and \s-1META\s0 variables. .SH "SETTING THE STAGE: CONFIGURATION AND LOGGING" .IX Header "SETTING THE STAGE: CONFIGURATION AND LOGGING" .SS "Configuration and environments" .IX Subsection "Configuration and environments" Configuring a Dancer application can be done in many ways. The easiest one (and maybe the dirtiest) is to put all your settings statements at the top of your script, before calling the \fBdance()\fR method. .PP Other ways are possible. You can define all your settings in the file `appdir/config.yml'. For this, you must have installed the \s-1YAML\s0 module, and of course, write the config file in \s-1YAML.\s0 .PP That's better than the first option, but it's still not perfect as you can't switch easily from one environment to another without rewriting the config.yml file. .PP The better way is to have one config.yml file with default global settings, like the following: .PP .Vb 3 \& # appdir/config.yml \& logger: \*(Aqfile\*(Aq \& layout: \*(Aqmain\*(Aq .Ve .PP And then write as many environment files as you like in \f(CW\*(C`appdir/environments\*(C'\fR. That way the appropriate environment config file will be loaded according to the running environment (if none is specified, it will be 'development'). .PP Note that you can change the running environment using the \f(CW\*(C`\-\-environment\*(C'\fR command line switch. .PP Typically, you'll want to set the following values in a development config file: .PP .Vb 4 \& # appdir/environments/development.yml \& log: \*(Aqdebug\*(Aq \& startup_info: 1 \& show_errors: 1 .Ve .PP And in a production one: .PP .Vb 4 \& # appdir/environments/production.yml \& log: \*(Aqwarning\*(Aq \& startup_info: 0 \& show_errors: 0 .Ve .SS "Accessing configuration information from your app" .IX Subsection "Accessing configuration information from your app" A Dancer application can use the 'config' keyword to easily access the settings within its config file, for instance: .PP .Vb 3 \& get \*(Aq/appname\*(Aq => sub { \& return "This is " . config\->{appname}; \& }; .Ve .PP This makes keeping your application's settings all in one place simple and easy. You shouldn't need to worry about implementing all that yourself :) .SS "Accessing configuration information from a separate script" .IX Subsection "Accessing configuration information from a separate script" You may well want to access your webapp's configuration from outside your webapp. You could, of course, use the \s-1YAML\s0 module of your choice and load your webapps's config.yml, but chances are that this is not convenient. .PP Use Dancer instead. Without any ado, magic or too big jumps, you can use the values from config.yml and some additional default values: .PP .Vb 4 \& # bin/script1.pl \& use Dancer \*(Aq:script\*(Aq; \& print "template:".config\->{template}."\en"; #simple \& print "log:".config\->{log}."\en"; #undef .Ve .PP Note that config\->{log} should result in an undef error on a default scaffold since you did not load the environment and in the default scaffold log is defined in the environment and not in config.yml. Hence undef. .PP If you want to load an environment you need to tell Dancer where to look for it. One way to do so, is to tell Dancer where the webapp lives. From there Dancer deduces where the config.yml file is (typically \f(CW$webapp\fR/config.yml). .PP .Vb 4 \& # bin/script2.pl \& use FindBin; \& use Cwd qw/realpath/; \& use Dancer \*(Aq:script\*(Aq; \& \& #tell the Dancer where the app lives \& my $appdir=realpath( "$FindBin::Bin/.."); \& \& Dancer::Config::setting(\*(Aqappdir\*(Aq,$appdir); \& Dancer::Config::load(); \& \& #getter \& print "environment:".config\->{environment}."\en"; #development \& print "log:".config\->{log}."\en"; #value from development environment .Ve .PP By default Dancer loads development environment (typically \&\f(CW$webapp\fR/environment/development.yml). In contrast to the example before, you do have a value from the development environment (environment/development.yml) now. Also note that in the above example Cwd and FindBin are used. They are likely to be already loaded by Dancer anyways, so it's not a big overhead. You could just as well hand over a simple path for the app if you like that better, e.g.: .PP .Vb 1 \& Dancer::Config::setting(\*(Aqappdir\*(Aq,\*(Aq/path/to/app/dir\*(Aq); .Ve .PP If you want to load an environment other than the default, try this: .PP .Vb 2 \& # bin/script2.pl \& use Dancer \*(Aq:script\*(Aq; \& \& #tell the Dancer where the app lives \& Dancer::Config::setting(\*(Aqappdir\*(Aq,\*(Aq/path/to/app/dir\*(Aq); \& \& #which environment to load \& config\->{environment}=\*(Aqproduction\*(Aq; \& \& Dancer::Config::load(); \& \& #getter \& print "log:".config\->{log}."\en"; #has value from production environment .Ve .PP By the way, you not only get values, you can also set values straightforward like we do above with config\->{environment}='production'. Of course, this value does not get written in any file; it only lives in memory and your webapp doesn't have access to it, but you can use it inside your script. .PP If you don't want to make your script environment-specific, or add extra arguments to it, you can also set the environment using a shell variable, \s-1DANCER_ENVIRONMENT.\s0 See also \*(L"DANCER_CONFDIR\-and\-DANCER_ENVDIR\*(R" in Dancer::Config .SS "Logging" .IX Subsection "Logging" \fIConfiguring logging\fR .IX Subsection "Configuring logging" .PP It's possible to log messages generated by the application and by Dancer itself. .PP To start logging, select the logging engine you wish to use with the \f(CW\*(C`logger\*(C'\fR setting; Dancer includes built-in log engines named \f(CW\*(C`file\*(C'\fR and \f(CW\*(C`console\*(C'\fR, which log to a logfile and to the console respectively. .PP To enable logging to a file, add the following to your config.yml: .PP .Vb 1 \& logger: \*(Aqfile\*(Aq .Ve .PP Then you can choose which kind of messages you want to actually log: .PP .Vb 6 \& log: \*(Aqcore\*(Aq # will log all messages, including messages from \& # Dancer itself \& log: \*(Aqdebug\*(Aq # will log debug, info, warning and error messages \& log: \*(Aqinfo\*(Aq # will log info, warning and error messages \& log: \*(Aqwarning\*(Aq # will log warning and error messages \& log: \*(Aqerror\*(Aq # will log error messages .Ve .PP If you're using the \f(CW\*(C`file\*(C'\fR logging engine, a directory \f(CW\*(C`appdir/logs\*(C'\fR will be created and will host one logfile per environment. The log message contains the time it was written, the \s-1PID\s0 of the current process, the message and the caller information (file and line). .PP \fILogging your own messages\fR .IX Subsection "Logging your own messages" .PP Just call debug, warning, error or info with your message: .PP .Vb 1 \& debug "This is a debug message from my app."; .Ve .SH "RESTING" .IX Header "RESTING" .SS "Writing a \s-1REST\s0 application" .IX Subsection "Writing a REST application" With Dancer, it's easy to write \s-1REST\s0 applications. Dancer provides helpers to serialize and deserialize for the following data formats: .IP "\s-1JSON\s0" 4 .IX Item "JSON" .PD 0 .IP "\s-1YAML\s0" 4 .IX Item "YAML" .IP "\s-1XML\s0" 4 .IX Item "XML" .IP "Data::Dumper" 4 .IX Item "Data::Dumper" .PD .PP To activate this feature, you only have to set the \f(CW\*(C`serializer\*(C'\fR setting to the format you require, for instance in your config.yml: .PP .Vb 1 \& serializer: JSON .Ve .PP Or right in your code: .PP .Vb 1 \& set serializer => \*(AqJSON\*(Aq; .Ve .PP From now, all HashRefs or ArrayRefs returned by a route will be serialized to the format you chose, and all data received from \fB\s-1POST\s0\fR or \fB\s-1PUT\s0\fR requests will be automatically deserialized. .PP .Vb 5 \& get \*(Aq/hello/:name\*(Aq => sub { \& # this structure will be returned to the client as \& # {"name":"$name"} \& return {name => params\->{name}}; \& }; .Ve .PP It's possible to let the client choose which serializer he wants to use. For this, use the \fBmutable\fR serializer, and an appropriate serializer will be chosen from the \fBContent-Type\fR header. .PP It's also possible to return a custom error, using the send_error keyword.. When you don't use a serializer, the \f(CW\*(C`send_error\*(C'\fR function will take a string as the first parameter (the message), and an optional \s-1HTTP\s0 code. When using a serializer, the message can be a string, an ArrayRef or a HashRef: .PP .Vb 7 \& get \*(Aq/hello/:name\*(Aq => sub { \& if (...) { \& send_error("you can\*(Aqt do that"); \& # or \& send_error({reason => \*(Aqaccess denied\*(Aq, message => "no"}); \& } \& }; .Ve .PP The content of the error will be serialized using the appropriate serializer. .SS "Deploying your Dancer applications" .IX Subsection "Deploying your Dancer applications" For examples on deploying your Dancer applications including standalone, behind proxy/load\-balancing software, and using common web servers including Apache to run via CGI/FastCGI etc, see Dancer::Deployment. .SH "DANCER ON THE STAGE: DEPLOYMENT" .IX Header "DANCER ON THE STAGE: DEPLOYMENT" .SS "Plack middlewares" .IX Subsection "Plack middlewares" If you deploy with Plack and use some Plack middlewares, you can enable them directly from Dancer's configuration files. .PP \fIGeneric middlewares\fR .IX Subsection "Generic middlewares" .PP To enable middlewares in Dancer, you just have to set the plack_middlewares setting like the following: .PP .Vb 3 \& set plack_middlewares => [ \& [ \*(AqSomeMiddleware\*(Aq => qw(some options for somemiddleware) ], \& ]; .Ve .PP For instance, if you want to enable Plack::Middleware::Debug in your Dancer application, all you have to do is to set \f(CW\*(C`plack_middlewares\*(C'\fR like that: .PP .Vb 3 \& set plack_middlewares => [ \& [ \*(AqDebug\*(Aq => ( \*(Aqpanels\*(Aq => [qw(DBITrace Memory Timer)] ) ], \& ]; .Ve .PP Of course, you can also put this configuration into your config.yml file, or even in your environment configuration files: .PP .Vb 10 \& # environments/development.yml \& ... \& plack_middlewares: \& \- \& \- Debug # first element of the array is the name of the middleware \& \- panels # following elements are the configuration of the middleware \& \- \& \- DBITrace \& \- Memory \& \- Timer .Ve .PP \fIPath-based middlewares\fR .IX Subsection "Path-based middlewares" .PP If you want to set up a middleware for a specific path, you can do that using \&\f(CW\*(C`plack_middlewares_map\*(C'\fR. You'll need Plack::App::URLMap to do that. .PP .Vb 3 \& plack_middlewares_map: \& \*(Aq/\*(Aq: [\*(AqDebug\*(Aq] \& \*(Aq/timer\*(Aq: [\*(AqTimer\*(Aq], .Ve .SH "DEVELOPMENT TOOLS" .IX Header "DEVELOPMENT TOOLS" .SS "Auto-reloading code" .IX Subsection "Auto-reloading code" When you are furiously hacking on your Dancer app, it might come in handy to have the application auto-detect changes in the code and reload itself. .PP To do that, you can use Plack::Loader::Shotgun, Plack::Middleware::Refresh, or plackup with the \f(CW\*(C`\-r\*(C'\fR switch: .PP .Vb 1 \& plackup \-r bin/appl.pl (will restart the app whenever a file in ./bin or ./lib is modified .Ve .SH "AUTHOR" .IX Header "AUTHOR" Dancer Core Developers .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2010 by Alexis Sukrieh. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.