Mojolicious::Guides::Tutorial - Get started with Mojolicious
Mojolicious::Guides::Tutorial - Mojoliciousをはじめよう
A quick example-driven introduction to the wonders of Mojolicious::Lite. Almost everything you'll learn here also applies to full Mojolicious applications.
Mojolicious::Liteの特徴を簡単なサンプルで紹介していきます。 ここで学んだことは、ほとんどすべてがフルバージョンのMojoliciousアプリケーションにも当てはまります。
チュートリアルはMojolicious::Guidesのはじめの章です。 その他のガイドでは、各トピックについて深く掘り下げます; たとえば、Mojolicious::Liteのプロトタイプをしっかり構築したMojolicious アプリケーションに育てるためのgrowing、またはrouting、 rendering、その他にもたくさんあります。 これを読み終わった後は、残りのガイドを読むことををおすすめします。
Hello World¶
かんたんなHello Worldアプリケーションはこのようになります; strict, warnings, utf8 、Perl 5.10のfeatures が自動的に有効になり、 functions がいくつかインポートされます; Mojolicious::Liteを使うと、あなたのスクリプトは完全な機能を備えたウェブアプリケーションになります。
#!/usr/bin/env perl
use Mojolicious::Lite;
get '/' => sub {
my $c = shift;
$c->render(text => 'Hello World!');
};
app->start;
Mojolicious::Command::Author::generate::lite_app には、小さなアプリケーションサンプルを生成するためのヘルパーコマンドがあります。
$ mojo generate lite_app myapp.pl
コマンド¶
Many different commands are automatically available from the command line. CGI and PSGI environments can even be detected and will usually just work without commands.
多くのcommands が自動的にコマンドラインから利用できるようになります。 CGIまたはPSGI のどちらの環境であるかは自動的に検知されるため、通常はコマンドで指定しなくても動作します。
$ ./myapp.pl daemon
Server available at http://127.0.0.1:3000
$ ./myapp.pl daemon -l http://*:8080
Server available at http://127.0.0.1:8080
$ ./myapp.pl cgi
...CGI output...
$ ./myapp.pl get /
Hello World!
$ ./myapp.pl
...List of available commands (or automatically detected environment)...
$ ./myapp.pl
...利用可能なコマンドが表示(または自動的に環境が検知される)...
A call to "start" in Mojolicious (app->start), which starts the command system, should be the last expression in your application, because its return value can be significant.
"start" in Mojolicious (app->start)を呼び出すと、コマンドシステムが開始されます; この呼び出しはアプリケーションの最後に置くべきです; というのは、返り値が大きな影響をもつ場合があるからです。
# Use @ARGV to pick a command
app->start;
# @ARGVを使ってコマンドを取得する
app->start;
# Start the "daemon" command
app->start('daemon', '-l', 'http://*:8080');
# "daemon"コマンドを開始する
app->start('daemon', '-l', 'http://*:8080');
リロード¶
Your application will automatically reload itself if you start it with the morbo development web server, so you don't have to restart the server after every change.
開発用サーバーのmorboでアプリケーションを起動すれば、 アプリケーションは自動的にリロードされます; ソースコードを変更した後に毎回サーバを再起動させる必要はありません。
$ morbo ./myapp.pl
Server available at http://127.0.0.1:3000
アプリケーションのデプロイ方法について詳しい情報は、 "DEPLOYMENT" in Mojolicious::Guides::Cookbookの項目を見てください。
ルーティング(Routes)¶
Routes are basically just fancy paths that can contain different kinds of placeholders and usually lead to an action, if they match the path part of the request URL. The first argument passed to all actions ($c) is a Mojolicious::Controller object, containing both the HTTP request and response.
ルーティング(routes)とは、一般的にいうと異なる種類のプレースホルダを含むことのできる仮想的なパスのことです; 通常はアクションにつながっており、リクエストURLのパス部分にマッチしたときに実行されます。 すべてのアクション ($c) に渡される第一引数は、Mojolicious::Controllerのインスタンスです。これにはHTTPリクエストとレスポンスが含まれています。
use Mojolicious::Lite;
# Route leading to an action that renders some text
get '/foo' => sub {
my $c = shift;
$c->render(text => 'Hello World!');
};
# テキストをレンダリングするアクションへのルーティング
get '/foo' => sub {
my $c = shift;
$c->render(text => 'Hello World!');
};
app->start;
レスポンスコンテントの多くは "render" in Mojolicious::Controllerを使ったアクションによって生成されます; 詳しくは後ほど。
GET/POSTパラメーター¶
すべてのGETとPOSTパラメーターは"param" in Mojolicious::Controllerを通じてアクセスできます。
use Mojolicious::Lite;
# /foo?user=sri
get '/foo' => sub {
my $c = shift;
my $user = $c->param('user');
$c->render(text => "Hello $user.");
};
app->start;
スタッシュとテンプレート¶
"stash" in Mojolicious::Controllerはデータをテンプレートに渡すために利用します; テンプレートはDATAセクションに埋め込むことができます。 template、text、dataなどのいくつかがスタッシュの値として予約されており、"render" in Mojolicious::Controllerで使われて、レスポンスをどのように生成するかが決定されます。
use Mojolicious::Lite;
# Route leading to an action that renders a template
get '/foo' => sub {
my $c = shift;
$c->stash(one => 23);
$c->render(template => 'magic', two => 24);
};
# テンプレートを描画するアクションに至るルート
get '/foo' => sub {
my $c = shift;
$c->stash(one => 23);
$c->render(template => 'magic', two => 24);
};
app->start;
__DATA__
@@ magic.html.ep
The magic numbers are <%= $one %> and <%= $two %>.
テンプレートについて詳しい情報は "Embedded Perl" in Mojolicious::Guides::Rendering の項を見てください。
HTTP¶
"req" in Mojolicious::Controllerと"res" in Mojolicious::Controller を使って、HTTPの機能と情報のすべてに完全にアクセスすることができます。
use Mojolicious::Lite;
# Access request information
get '/agent' => sub {
my $c = shift;
my $host = $c->req->url->to_abs->host;
my $ua = $c->req->headers->user_agent;
$c->render(text => "Request by $ua reached $host.");
};
# リクエストの情報にアクセス
get '/agent' => sub {
my $c = shift;
my $host = $c->req->url->to_abs->host;
my $ua = $c->req->headers->user_agent;
$c->render(text => "Request by $ua reached $host.");
};
# Echo the request body and send custom header with response
post '/echo' => sub {
my $c = shift;
$c->res->headers->header('X-Bender' => 'Bite my shiny metal ass!');
$c->render(data => $c->req->body);
};
# リクエストボディをエコーして、レスポンスのついたカスタムヘッダを送信
post '/echo' => sub {
my $c = shift;
$c->res->headers->header('X-Bender' => 'Bite my shiny metal ass!');
$c->render(data => $c->req->body);
};
app->start;
Mojolicious::Command::getを使って、コマンドラインからより発展的なサンプルをテストできます。
$ ./myapp.pl get -v -M POST -c 'test' /echo
JSON¶
JSON is the most commonly used data-interchange format for web services. Mojolicious loves JSON and comes with the possibly fastest pure-Perl implementation Mojo::JSON built right in, which is accessible through "json" in Mojo::Message as well as the reserved stash value json.
JSONは、ウェブサービスでもっともよく使われるデータ交換フォーマットです。 MojoliciousはJSONが大好きです; ピュアPerlの実装ではおそらく最速の Mojo::JSON が組み込まれており、"json" in Mojo::Message または予約済みスタッシュ値のjsonによってアクセスできます。
use Mojolicious::Lite;
# Modify the received JSON document and return it
put '/reverse' => sub {
my $c = shift;
my $hash = $c->req->json;
$hash->{message} = reverse $hash->{message};
$c->render(json => $hash);
};
# 受け取ったJSONドキュメントを変更して返す
put '/reverse' => sub {
my $c = shift;
my $hash = $c->req->json;
$hash->{message} = reverse $hash->{message};
$c->render(json => $hash);
};
app->start;
コマンドラインからMojolicious::Command::getを使ってJSONドキュメントを送信できます。
$ ./myapp.pl get -M PUT -c '{"message":"Hello Mojo!"}' /reverse
Built-in exception and not_found pages¶
(組み込みの例外(exception)とノットファウンド(not_found)ページ)
During development you will encounter these pages whenever you make a mistake, they are gorgeous and contain a lot of valuable information that will aid you in debugging your application.
開発中、間違いを犯したときはいつでも、このページに遭遇するでしょう; ここには、素晴らしい、アプリケーションのデバックに役立つ情報がたくさん含まれています。
use Mojolicious::Lite;
# Not found (404)
get '/missing' => sub { shift->render(template => 'does_not_exist') };
# Exception (500)
get '/dies' => sub { die 'Intentional error' };
app->start;
Mojolicious::Command::get でCSSセレクタを使えば、実際に知りたい情報だけを取り出すこともできます。
$ ./myapp.pl get /dies '#error'
And don't worry about revealing too much information on these pages, they are only available during development, and will be replaced automatically with pages that don't reveal any sensitive information in a production environment.
ページに情報が見えすぎるからといって心配しないでください; これが有効になるのは開発中だけです; プロダクション環境では、大切な情報が表示されないページに自動的に置き換わります。
ルーティング名¶
すべてのルーティング(routes)には名前を付けることができます; 名前を付けることによってテンプレートの自動検出や"url_for" in Mojolicious::Controllerによる逆引きができるようになり、"link_to" in Mojolicious::Plugin::TagHelpersなど、多くのヘルパーやメソッドがこれに基づいて動きます。
use Mojolicious::Lite;
# Render the template "index.html.ep"
get '/' => sub {
my $c = shift;
$c->render;
} => 'index';
# "index.html.ep"というテンプレートを描画
get '/' => sub {
my $c = shift;
$c->render;
} => 'index';
# Render the template "hello.html.ep"
get '/hello';
# "hello.html.ep"というテンプレートを描画
get '/hello';
app->start;
__DATA__
@@ index.html.ep
<%= link_to Hello => 'hello' %>.
<%= link_to Reload => 'index' %>.
@@ hello.html.ep
Hello World!
Nameless routes get an automatically generated one assigned that is simply equal to the route itself without non-word characters.
名前がないルートには、自動生成されたルート名が割り当てられます; この名前は、ルート自身の名前からノンワード文字を除いたものと同じです。
レイアウト¶
テンプレートにはレイアウトを持たせることができます; レイアウトは"layout" in Mojolicious::Plugin::DefaultHelpersヘルパーを使って選択することができ、"content" in Mojolicious::Plugin::DefaultHelpersヘルパーを使って現在のテンプレートの結果を入れることができます。
use Mojolicious::Lite;
get '/with_layout';
app->start;
__DATA__
@@ with_layout.html.ep
% title 'Green';
% layout 'green';
Hello World!
@@ layouts/green.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
スタッシュや"title" in Mojolicious::Plugin::DefaultHelpersのようなヘルパーを使うと、追加のデータをレイアウトに渡せます。
ブロック¶
Template blocks can be used like normal Perl functions and are always delimited by the begin and end keywords, they are the foundation for many helpers.
テンプレートブロックは通常のPerl関数のように利用でき、常にbeginとendというキーワードで区切ります; これは多くのヘルパーの基盤になっています。
use Mojolicious::Lite;
get '/with_block' => 'block';
app->start;
__DATA__
@@ block.html.ep
% my $link = begin
% my ($url, $name) = @_;
Try <%= link_to $url => begin %><%= $name %><% end %>.
% end
<!DOCTYPE html>
<html>
<head><title>Sebastians frameworks</title></head>
<body>
%= $link->('http://mojolicious.org', 'Mojolicious')
%= $link->('http://catalystframework.org', 'Catalyst')
</body>
</html>
ヘルパー¶
Helpers are little functions you can create with the keyword "helper" in Mojolicious::Lite and reuse throughout your whole application, from actions to templates.
ヘルパーは "helper" in Mojolicious::Lite キーワードで作ることができる小さな関数です; アクションからテンプレートまでアプリケーション全体において利用することができます。
use Mojolicious::Lite;
# A helper to identify visitors
helper whois => sub {
my $c = shift;
my $agent = $c->req->headers->user_agent || 'Anonymous';
my $ip = $c->tx->remote_address;
return "$agent ($ip)";
};
# 訪問者を特定するヘルパー
helper whois => sub {
my $c = shift;
my $agent = $c->req->headers->user_agent || 'Anonymous';
my $ip = $c->tx->remote_address;
return "$agent ($ip)";
};
# Use helper in action and template
get '/secret' => sub {
my $c = shift;
my $user = $c->whois;
$c->app->log->debug("Request from $user");
};
# アクションとテンプレートのなかでヘルパーを使う
get '/secret' => sub {
my $c = shift;
my $user = $c->whois;
$c->app->log->debug("Request from $user");
};
app->start;
__DATA__
@@ secret.html.ep
We know who you are <%= whois %>.
すべての組み込みヘルパーのリストは、 Mojolicious::Plugin::DefaultHelpers と Mojolicious::Plugin::TagHelpersにあります。
プレースホルダー¶
ルーティング(routes)プレースホルダを使用すると、区切り文字の / あるいは . が出現するまでの部分を、リクエストパスからキャプチャできます。 結果は"stash" in Mojolicious::Controllerとparamを通じて利用できます。
use Mojolicious::Lite;
# /foo/test
# /foo/test123
get '/foo/:bar' => sub {
my $c = shift;
my $bar = $c->stash('bar');
$c->render(text => "Our :bar placeholder matched $bar");
};
# /testsomething/foo
# /test123something/foo
get '/<:bar>something/foo' => sub {
my $c = shift;
my $bar = $c->param('bar');
$c->render(text => "Our :bar placeholder matched $bar");
};
app->start;
To separate them from the surrounding text, you can surround your placeholders with < and >, which also makes the colon prefix optional.
プレースホルダーを周囲の文字列と区別するためには、 < と > で囲みます; こうした場合、プレフィックスのコロンはオプションになります。
リラックスプレースホルダー¶
Relaxed placeholders allow matching of everything until a / occurs, similar to the regular expression ([^/]+).
リラックスプレースホルダーを使えば、 /が出現するまでのすべてにマッチさせることができます; これは正規表現の([^/]+)に似ています。
use Mojolicious::Lite;
# /hello/test
# /hello/test.html
get '/hello/#you' => 'groovy';
app->start;
__DATA__
@@ groovy.html.ep
Your name is <%= $you %>.
ワイルドカードプレースホルダー¶
Wildcard placeholders allow matching absolutely everything, including / and ., similar to the regular expression (.+).
ワイルドカードプレースホルダを使用すると、/と.を含むすべてにマッチさせることができます; 正規表現の(.+)に似ています。
use Mojolicious::Lite;
# /hello/test
# /hello/test123
# /hello/test.123/test/123
get '/hello/*you' => 'groovy';
use Mojolicious::Lite;
# /hello/test123
# /hello/test.123/test/123
get '/hello/*you' => 'groovy';
app->start;
__DATA__
@@ groovy.html.ep
Your name is <%= $you %>.
HTTPメソッド¶
ルーティングは "/"get"" in Mojolicious::Lite や "any" in Mojolicious::Liteといったキーワードによって特定のリクエストメソッドに限定できます。
use Mojolicious::Lite;
# GET /hello
get '/hello' => sub {
my $c = shift;
$c->render(text => 'Hello World!');
};
# PUT /hello
put '/hello' => sub {
my $c = shift;
my $size = length $c->req->body;
$c->render(text => "You uploaded $size bytes to /hello.");
};
# GET|POST|PATCH /bye
any ['GET', 'POST', 'PATCH'] => '/bye' => sub {
my $c = shift;
$c->render(text => 'Bye World!');
};
# * /whatever
any '/whatever' => sub {
my $c = shift;
my $method = $c->req->method;
$c->render(text => "You called /whatever with $method.");
};
app->start;
プレースホルダーのオプション¶
All placeholders require a value, but by assigning them default values you can make capturing optional.
すべてのプレースホルダーは値を必要としますが、プレースホルダーにデフォルト値を設定することによりキャプチャをオプショナルなものにすることができます。
use Mojolicious::Lite;
# /hello
# /hello/Sara
get '/hello/:name' => {name => 'Sebastian', day => 'Monday'} => sub {
my $c = shift;
$c->render(template => 'groovy', format => 'txt');
};
app->start;
__DATA__
@@ groovy.txt.ep
My name is <%= $name %> and it is <%= $day %>.
Default values that don't belong to a placeholder simply get merged into the stash all the time.
プレースホルダーに所属しないデフォルト値は、いつでも単純にスタッシュにマージされます。
制約的なプレースホルダー¶
A very easy way to make placeholders more restrictive are alternatives, you just make a list of possible values.
プレースホルダーにより多くの制約を加えるには、選択肢を使うのが一番簡単です; 候補となる値のリストを作るだけでOKです。
use Mojolicious::Lite;
# /test
# /123
any '/:foo' => [foo => ['test', '123']] => sub {
my $c = shift;
my $foo = $c->param('foo');
$c->render(text => "Our :foo placeholder matched $foo");
};
app->start;
All placeholders get compiled to a regular expression internally, this process can also be customized. Just make sure not to use ^ and $, or capturing groups (...), non-capturing groups (?:...) are fine though.
すべてのプレースホルダーは、内部で正規表現にコンパイルされます; この処理はカスタマイズすることもできます。 ^と$を使ったり、(...)でグループのキャプチャは行わないでください; けれどもキャプチャしない(?:...)は大丈夫です。
use Mojolicious::Lite;
# /1
# /123
any '/:bar' => [bar => qr/\d+/] => sub {
my $c = shift;
my $bar = $c->param('bar');
$c->render(text => "Our :bar placeholder matched $bar");
};
app->start;
生成されたすべての正規表現は、Mojolicious::Command::routesで詳しく確認することができます。
$ ./myapp.pl routes -v
アンダー (Under)¶
Authentication and code shared between multiple routes can be realized easily with routes generated by "under" in Mojolicious::Lite. All following routes are only evaluated if the callback returned a true value.
認証や複数のルーティングの間でコードを共有するためには、"under" in Mojolicious::Lite構文を使う簡単です。 以降のすべてのルーティングは、このコールバックが真値を返したときだけ評価されます。
use Mojolicious::Lite;
# Authenticate based on name parameter
under sub {
my $c = shift;
# nameパラメータを元にした認証
under sub {
my $c = shift;
# Authenticated
my $name = $c->param('name') || '';
return 1 if $name eq 'Bender';
# 認証された
my $name = $c->param('name') || '';
return 1 if $name eq 'Bender';
# Not authenticated
$c->render(template => 'denied');
return undef;
};
# 認証されなかった
$c->render(template => 'denied');
return undef;
};
# Only reached when authenticated
get '/' => 'index';
app->start;
__DATA__
@@ denied.html.ep
You are not Bender, permission denied.
@@ index.html.ep
Hi Bender.
Prefixing multiple routes is another good use for it.
複数のルーティングをあらかじめ決めるために使うのもまた良い利用方法です。
use Mojolicious::Lite;
# /foo
under '/foo';
# /foo/bar
get '/bar' => {text => 'foo bar'};
# /foo/baz
get '/baz' => {text => 'foo baz'};
# / (reset)
under '/' => {msg => 'whatever'};
# /bar
get '/bar' => {inline => '<%= $msg %> works'};
app->start;
"group" in Mojolicious::Liteで関連するルーティングをグループ化することもできます; これによって、"under" in Mojolicious::Liteで生成したルートをネストできるようになります。
use Mojolicious::Lite;
# Global logic shared by all routes
under sub {
my $c = shift;
return 1 if $c->req->headers->header('X-Bender');
$c->render(text => "You're not Bender.");
return undef;
};
# すべてのルートで共有されるグローバルなロジック
under sub {
my $c = shift;
return 1 if $c->req->headers->header('X-Bender');
$c->render(text => "You're not Bender.");
return undef;
};
# Admin section
group {
# Adminの部分
group {
# Local logic shared only by routes in this group
under '/admin' => sub {
my $c = shift;
return 1 if $c->req->headers->header('X-Awesome');
$c->render(text => "You're not awesome enough.");
return undef;
};
# グループ内のルートだけに共有されるローカルなロジック
under '/admin' => sub {
my $c = shift;
return 1 if $c->req->headers->header('X-Awesome');
$c->render(text => "You're not awesome enough.");
return undef;
};
# GET /admin/dashboard
get '/dashboard' => {text => 'Nothing to see here yet.'};
};
# GET /welcome
get '/welcome' => {text => 'Hi Bender.'};
app->start;
Formats can be automatically detected from file extensions like .html, they are used to find the right template and generate the correct Content-Type header.
フォーマット(formats)は、.htmlなどのファイル拡張子によって自動的に検出されます; フォーマットは正しいテンプレートを探したり、正確なContent-Typeヘッダーを生成するために使用されます。
use Mojolicious::Lite;
# /detection
# /detection.html
# /detection.txt
get '/detection' => sub {
my $c = shift;
$c->render(template => 'detected');
};
app->start;
__DATA__
@@ detected.html.ep
<!DOCTYPE html>
<html>
<head><title>Detected</title></head>
<body>HTML was detected.</body>
</html>
@@ detected.txt.ep
TXT was detected.
The default format is html, and restrictive placeholders can be used to limit possible values.
デフォルトのフォーマットは htmlです; プレースホルダで制限すれば、取りうる値を限定できます。
use Mojolicious::Lite;
# /hello.json
# /hello.txt
get '/hello' => [format => ['json', 'txt']] => sub {
my $c = shift;
return $c->render(json => {hello => 'world'})
if $c->stash('format') eq 'json';
$c->render(text => 'hello world');
};
app->start;
Or you can just disable format detection with a special type of restrictive placeholder.
フォーマットの検知は、特別なタイプのプレースホルダーを使うことで無効にすることもできます。
use Mojolicious::Lite;
# /hello
get '/hello' => [format => 0] => {text => 'No format detection.'};
# Disable detection and allow the following routes to re-enable it on demand
under [format => 0];
# 検出を無効にして、以降のルートにおいて必要であれば再び有効にする
under [format => 0];
# /foo
get '/foo' => {text => 'No format detection again.'};
# /bar.txt
get '/bar' => [format => 'txt'] => {text => ' Just one format.'};
app->start;
コンテントネゴシエーション¶
異なる方法で表現されるリソースや本当にRESTfulなコンテントネゴーシエーションが必要な場合は、"respond_to" in Mojolicious::Plugin::DefaultHelpersを使用することもできます。
use Mojolicious::Lite;
# /hello (Accept: application/json)
# /hello (Accept: application/xml)
# /hello.json
# /hello.xml
# /hello?format=json
# /hello?format=xml
get '/hello' => sub {
my $c = shift;
$c->respond_to(
json => {json => {hello => 'world'}},
xml => {text => '<hello>world</hello>'},
any => {data => '', status => 204}
);
};
app->start;
MIMEタイプのマッピングは、"types" in Mojoliciousによって拡張したり、変更したりすることができます。
app->types->type(rdf => 'application/rdf+xml');
静的ファイル¶
Similar to templates, but with only a single file extension and optional Base64 encoding, static files can be inlined in the DATA section and are served automatically.
テンプレートに似て、静的ファイルはDATAセクションの中にインラインで記述することができ、自動的にサーブされます; ただし、使える拡張子が1種類に限られるのと、Base64エンコーディングが使える点が異なります。
use Mojolicious::Lite;
app->start;
__DATA__
@@ something.js
alert('hello!');
@@ test.txt (base64)
dGVzdCAxMjMKbGFsYWxh
External static files are not limited to a single file extension and will be served automatically from a public directory if it exists.
外部に置いた静的ファイルは、拡張子が1種類に制限されず、publicディレクトリが存在すればそこから自動的にサーブされます。
$ mkdir public
$ mv something.js public/something.js
$ mv mojolicious.tar.gz public/mojolicious.tar.gz
Both have a higher precedence than routes for GET and HEAD requests. Content negotiation with Range, If-None-Match and If-Modified-Since headers is supported as well and can be tested very easily with Mojolicious::Command::get.
両方とも優先度はGET、HEADリクエストのルーティングよりも高くなります。 Range、If-None-Match、If-Modified-Sinceヘッダー によるコンテンツネゴシエーションにも対応していて、 Mojolicious::Command::getで簡単にテストできます。
$ ./myapp.pl get /something.js -v -H 'Range: bytes=2-4'
外部テンプレート¶
External templates will be searched by the renderer in a templates directory if it exists.
外部テンプレートは、レンダラによってtemplates ディレクトリから検索されます。
$ mkdir -p templates/foo
$ echo 'Hello World!' > templates/foo/bar.html.ep
They have a higher precedence than templates in the DATA section.
これらはDATAセクションにあるテンプレートよりも優先されます。
use Mojolicious::Lite;
# Render template "templates/foo/bar.html.ep"
any '/external' => sub {
my $c = shift;
$c->render(template => 'foo/bar');
};
# "templates/foo/bar.html.ep"というテンプレートを描画する
any '/external' => sub {
my $c = shift;
$c->render(template => 'foo/bar');
};
app->start;
ホーム¶
You can use "home" in Mojolicious to interact with the directory your application considers its home. This is the directory it will search for public and templates directories, but you can use it to store all sorts of application specific data.
"home" in Mojolicious を使うと、アプリケーションがホームとしているディレクトリにアクセスできます。 ホームディレクトリは、アプリケーションがpublic, templatesディレクトリを検索する場所です; ここにあらゆる種類のアプリケーションデータを保存することもできます。
$ mkdir cache
$ echo 'Hello World!' > cache/hello.txt
Mojo::Home には Mojo::Fileから継承した便利なメソッドがたくさんあります; たとえば、"child" in Mojo::Fileや"slurp" in Mojo::Fileは、アプリケーションを様々なオペレーティングシステムにまたがって使用できるようにしています。
use Mojolicious::Lite;
# Load message into memory
my $hello = app->home->child('cache', 'hello.txt')->slurp;
# メッセージをメモリに読み込む
my $hello = app->home->child('cache', 'hello.txt')->slurp;
# Display message
get '/' => sub {
my $c = shift;
$c->render(text => $hello);
};
# メッセージを表示する
get '/' => sub {
my $c = shift;
$c->render(text => $hello);
};
Mojolicious::Command::eval を使うことでも、コマンドラインからアプリケーションを検証できます。
$ ./myapp.pl eval -v 'app->home'
Mojolicious::Plugin::HeaderCondition を使用すれば、より強力なルーティングを構築できます。
use Mojolicious::Lite;
# Firefox
get '/foo' => (agent => qr/Firefox/) => sub {
my $c = shift;
$c->render(text => 'Congratulations, you are using a cool browser.');
};
# Internet Explorer
get '/foo' => (agent => qr/Internet Explorer/) => sub {
my $c = shift;
$c->render(text => 'Dude, you really need to upgrade to Firefox.');
};
# http://mojolicious.org/bar
get '/bar' => (host => 'mojolicious.org') => sub {
my $c = shift;
$c->render(text => 'Hello Mojolicious.');
};
app->start;
セッション¶
Cookie-based sessions just work out of the box, as soon as you start using them through the helper "session" in Mojolicious::Plugin::DefaultHelpers. Just be aware that all session data gets serialized with Mojo::JSON and stored client-side, with a cryptographic signature to prevent tampering.
"session" in Mojolicious::Plugin::DefaultHelpersヘルパーを使うとすぐに、クッキーをベースとしたセッションが機能します。 すべてのセッションデータはMojo::JSONでシリアライズされ、 クライアントサイドに保存されることを意識しておいてください。 改ざんを防ぐために、暗号化された署名がついています。
use Mojolicious::Lite;
# Access session data in action and template
get '/counter' => sub {
my $c = shift;
$c->session->{counter}++;
};
# アクションとテンプレートの中のセッションデータへのアクセス
get '/counter' => sub {
my $c = shift;
$c->session->{counter}++;
};
app->start;
__DATA__
@@ counter.html.ep
Counter: <%= session 'counter' %>
署名付き(signed)クッキーを本当に改ざんできなくするには、"secrets" in Mojoliciousをカスタムして使用してください。
app->secrets(['My secret passphrase here']);
ファイルアップロード¶
ファイルは、multipart/form-dataリクエストを通してアップロードされると、自動的に "param" in Mojolicious::ControllerからMojo::Uploadのインスタンスとして利用可能になります。 メモリの使用率を気にする必要はありません; 250KBを超えるすべてのファイルは自動的に一時ファイルに保存されるからです。 HTMLフォームを効率的に構築するために、 "form_for" in Mojolicious::Plugin::TagHelpersのような タグヘルパーを使うこともできます。
use Mojolicious::Lite;
# Upload form in DATA section
get '/' => 'form';
# DATAセクションのformをアップロード
get '/' => 'form';
# Multipart upload handler
post '/upload' => sub {
my $c = shift;
# Multipartのアップロードのハンドラ
post '/upload' => sub {
my $c = shift;
# Check file size
return $c->render(text => 'File is too big.', status => 200)
if $c->req->is_limit_exceeded;
# ファイルサイズのチェック
return $c->render(text => 'File is too big.', status => 200)
if $c->req->is_limit_exceeded;
# Process uploaded file
return $c->redirect_to('form') unless my $example = $c->param('example');
my $size = $example->size;
my $name = $example->filename;
$c->render(text => "Thanks for uploading $size byte file $name.");
};
# アップロードしたファイルを処理
return $c->redirect_to('form') unless my $example = $c->param('example');
my $size = $example->size;
my $name = $example->filename;
$c->render(text => "Thanks for uploading $size byte file $name.");
};
app->start;
__DATA__
@@ form.html.ep
<!DOCTYPE html>
<html>
<head><title>Upload</title></head>
<body>
%= form_for upload => (enctype => 'multipart/form-data') => begin
%= file_field 'example'
%= submit_button 'Upload'
% end
</body>
</html>
極端に大きなファイルから保護するために、デフォルトで16MBの制限があります。 サイズは"max_request_size" in Mojolicious 属性で変更できます。
# Increase limit to 1GiB
app->max_request_size(1073741824);
# 制限を1GBに増やす
app->max_request_size(1073741824);
ユーザーエージェント¶
Mojo::UserAgentは、完全に機能を備えたHTTP 1.1とWebSocketの組み込みのユーザーエージェントです; "ua" in Mojolicious::Plugin::DefaultHelpersを通して利用できます。 特にMojo::JSONとMojo::DOMの組み合わせはとても強力なツールになります。
use Mojolicious::Lite;
# Blocking
get '/headers' => sub {
my $c = shift;
my $url = $c->param('url') || 'https://mojolicious.org';
my $dom = $c->ua->get($url)->result->dom;
$c->render(json => $dom->find('h1, h2, h3')->map('text')->to_array);
};
# ブロッキング
get '/headers' => sub {
my $c = shift;
my $url = $c->param('url') || 'https://mojolicious.org';
my $dom = $c->ua->get($url)->result->dom;
$c->render(json => $dom->find('h1, h2, h3')->map('text')->to_array);
};
# Non-blocking
get '/title' => sub {
my $c = shift;
$c->ua->get('mojolicious.org' => sub {
my ($ua, $tx) = @_;
$c->render(data => $tx->result->dom->at('title')->text);
});
};
# ノンブロッキング
get '/title' => sub {
my $c = shift;
$c->ua->get('mojolicious.org' => sub {
my ($ua, $tx) = @_;
$c->render(data => $tx->result->dom->at('title')->text);
});
};
# Concurrent non-blocking
get '/titles' => sub {
my $c = shift;
my $mojo = $c->ua->get_p('https://mojolicious.org');
my $cpan = $c->ua->get_p('https://metacpan.org');
Mojo::Promise->all($mojo, $cpan)->then(sub {
my ($mojo, $cpan) = @_;
$c->render(json => {
mojo => $mojo->[0]->result->dom->at('title')->text,
cpan => $cpan->[0]->result->dom->at('title')->text
});
})->wait;
};
# 並列のノンブロッキング
get '/titles' => sub {
my $c = shift;
my $mojo = $c->ua->get_p('https://mojolicious.org');
my $cpan = $c->ua->get_p('https://metacpan.org');
Mojo::Promise->all($mojo, $cpan)->then(sub {
my ($mojo, $cpan) = @_;
$c->render(json => {
mojo => $mojo->[0]->result->dom->at('title')->text,
cpan => $cpan->[0]->result->dom->at('title')->text
});
})->wait;
};
app->start;
ユーザーエージェントについてより詳しい情報は、"USER AGENT" in Mojolicious::Guides::Cookbookの項目にあります。
WebSocket¶
WebSocketアプリケーションはこれまでに見たこともないくらい簡単です。"json" in Mojo::Transaction::WebSocketと同じイベントを、"on" in Mojolicious::Controllerを使って購読することによってメッセージを受信できます; メッセージを送信するには "send" in Mojolicious::Controllerを使います。
use Mojolicious::Lite;
websocket '/echo' => sub {
my $c = shift;
$c->on(json => sub {
my ($c, $hash) = @_;
$hash->{msg} = "echo: $hash->{msg}";
$c->send({json => $hash});
});
};
get '/' => 'index';
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head>
<title>Echo</title>
<script>
var ws = new WebSocket('<%= url_for('echo')->to_abs %>');
ws.onmessage = function (event) {
document.body.innerHTML += JSON.parse(event.data).msg;
};
ws.onopen = function (event) {
ws.send(JSON.stringify({msg: 'I ♥ Mojolicious!'}));
};
</script>
</head>
</html>
リアルタイムウェブ機能についてのより詳しい情報は、"REAL-TIME WEB" in Mojolicious::Guides::Cookbookにあります。
モード¶
ポータブルにデバッグメッセージを収集するために、"log" in MojoliciousメソッドでMojo::Logオブジェクトを利用できます; Mojoliciousの処理モードを変更することによって、後のプロダクション用の設定においてデバッグを自動的に無効化することができます; これは"mode" in Mojolicious属性によって読み取り可能です。
use Mojolicious::Lite;
# Prepare mode specific message during startup
my $msg = app->mode eq 'development' ? 'Development!' : 'Something else!';
# startupの間にモードに合ったメッセージを準備する
my $msg = app->mode eq 'development' ?'Development!' : 'Something else!';
get '/' => sub {
my $c = shift;
$c->app->log->debug('Rendering mode specific message');
$c->render(text => $msg);
};
app->log->debug('Starting application');
app->start;
The default operating mode will usually be development and can be changed with command line options or the MOJO_MODE and PLACK_ENV environment variables. A mode other than development will raise the log level from debug to info.
デフォルトの処理モードは通常 developmentですが、コマンドラインオプションか MOJO_MODEあるいはPLACK_ENV環境変数によって変更することもできます。 development以外のモードでは、ログレベルがdebugからinfoに上がります。
$ ./myapp.pl daemon -m production
All messages will be written to STDERR or a log/$mode.log file if a log directory exists.
すべてのメッセージはSTDERRに出力されるか、logディレクトリが存在する場合はlog/$mode.logに出力されます。
$ mkdir log
Mode changes also affect a few other aspects of the framework, such as the built-in exception and not_found pages. Once you switch modes from development to production, no sensitive information will be revealed on those pages anymore.
モードの変更は、exceptionやnot_foundテンプレートなどのフレームワークのその他の面に影響します。 モードをdevelopmentからproductionに切り替えると 、例外ページに機密情報が表示されなくなります。
テスト¶
Testing your application is as easy as creating a t directory and filling it with normal Perl tests like t/basic.t, which can be a lot of fun thanks to Test::Mojo.
アプリケーションをテストするのはとても簡単です; tディレクトリを作成して普通のPerlの単体テストを書くだけです。 Test::Mojoのおかげで、とても楽しいです。
use Test::More;
use Mojo::File 'path';
use Test::Mojo;
# Portably point to "../myapp.pl"
my $script = path(__FILE__)->dirname->sibling('myapp.pl');
my $t = Test::Mojo->new($script);
$t->get_ok('/')->status_is(200)->content_like(qr/Funky/);
done_testing();
Just run your tests with prove.
テストはproveで実行します。
$ prove -l -v
$ prove -l -v t/basic.t
もっと¶
さあ、Mojolicious::Guides を続けるか、Mojolicious wikiを見てみましょう。 多くの著者がたくさんのドキュメントやサンプルを書いています。
サポート¶
If you have any questions the documentation might not yet answer, don't hesitate to ask on the mailing list or the official IRC channel #mojo on irc.freenode.net (chat now!).
このドキュメントでわからない部分があれば、 mailing list かirc.freenode.net (chat now!)の公式IRCチャンネル #mojo まで気軽に質問してください。