天天看點

dancer cookbook 小議2

前過濾聲明的代碼在請求被傳遞到合适的路徑之前進行過濾。

hook 'before' => sub {

    var note => 'Hi there';

    request->path('/foo/oversee')

}; 

get '/foo/*' => sub {

    my ($match) = splat; # 'oversee';

    vars->{note}; # 'Hi there'

The above declares a before hook which uses var to set a variable which will later be available within the route handler, then amends the path of the request to /foo/oversee; this means that, whatever path was requested, it will be treated as though the path requested was /foo/oversee.

和重定向差不多,不管是什麼樣的路徑,都會被作為通路路徑/foo/oversee來對待。

Default route------->預設路由

In case you want to avoid a 404 error, 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.

The default route handler will handle any request that doesn't get served by any other route.

All you need to do is set up the following route as the last route:

any qr{.*} => sub {

    status 'not_found';

    template 'special_404', { path => request->path };

Then you can set up the template as such:

You tried to reach <% path %>, but it is unavailable at the moment. Please try again or contact us at our email at <...>. 

Using the auto_page feature for automatic route creation

For simple "static" pages, you can simply enable the auto_page config setting; this means that you need not declare a route handler for those pages; if a request is for /foo/bar, Dancer will check for a matching view (e.g. /foo/bar.tt and render it with the default layout etc if found. For full details, see the documentation for the auto_page setting.

Why should I use the Ajax plugin------->使用ajax插件

As an Ajax query is just a HTTP query, it's similar to a GET or POST route. You may ask yourself why you may want to use the ajax keyword (from the Dancer::Plugin::Ajax plugin) instead of a simple get.

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 HTML content. But you may also want to be able to call this same url from a javascript query using Ajax.

So, instead of having the following code:

get '/user/:user' => sub {

     if (request->is_ajax) { 

# create xml, set headers to text/xml, blablabla          header('Content-Type' => 'text/xml');

header('Cache-Control' =>  'no-store, no-cache, must-revalidate');          to_xml({...})

}else{

template users, {....}

}

you can have

    template users, {...}

and

ajax '/user/:user' => sub {

     to_xml({...}, RootName => undef);

Because it's an ajax query, you know you need to return a xml content, so the content type of the response is set for you.

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:

package myapp;

use Dancer ':syntax';

use myapp::admin; 

prefix undef; 

get '/' => sub {...};

1; 

package myapp::admin;

use Dancer ':syntax'; 

prefix '/admin'; 

get '/' => sub {...}; 

The following routes will be generated for us:

- get /

- get /admin/

- head /

- head /admin/ 

MUSCLE MEMORY: STORING DATA

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.

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: config file, add:

session: Simple 

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.

Dancer::Session::Simple backend将會話存儲在内容中,會話不持久,重新開機服務會話消失。

You can also use the Dancer::Session::YAML backend included with Dancer, which stores session data on disc in YAML files (since YAML is a nice human-readable format, it makes inspecting the contents of sessions a breeze):

Dancer::Session::YAML将會話資料存儲在磁盤中的YAML檔案中。由于YAML檔案是編排格式易讀的檔案,對于檢索裡面會話的内容非常容易。

session: YAML 

Or, to enable session support from within your code,

或者在代碼中啟用會話引擎。

set session => 'YAML'; 

(Controlling settings is best done from your config file, though). 'YAML' 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 YAML backend is a simple and easy to use example which stores session data in a YAML file in sessions).

You can then use the session keyword to manipulate the session:

使用關鍵字session來操作會話

Storing data in the session

Storing data in the session is as easy as:

儲存會話

session varname => 'value'; 

Retrieving data from the session

檢索會話

Retrieving data from the session is as easy as:

session('varname') Or, alternatively, session->{varname} 

Controlling where sessions are stored-------->會話存儲地

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 session_dir setting, which defaults to appdir/sessions if not specifically set.

預設情況下,對于将會話儲存在磁盤檔案中的引擎,将會話儲存在appdir/sessions目錄下,但是可以通過設定session_dir來修改儲存路徑。

If you need to control where session files are created, you can do so quickly and easily within your config file, for example:

session_dir: /tmp/dancer-sessions 

If the directory you specify does not exist, Dancer will attempt to create it for you.

如果制定的儲存會話的目錄不存在,那麼dancer會嘗試去建立她。

Destroying a session

繼續閱讀