サンプルで確認
組み込みアクションの呼び出されるタイミングをサンプルで確認してみましょう。「Root.pm」と「Bar.pm」にbeginアクションとautoアクションを追加します。
package HelloC::Controller::Root;
# 省略
sub begin :Private {
my ( $self, $c ) = @_;
$c->log->debug ( 'begin in Root' );
}
sub auto :Private {
my ( $self, $c ) = @_;
$c->log->debug ( 'auto in Root' );
}
package HelloC::Controller::Foo::Bar;
# 省略
sub begin :Private {
my ( $self, $c ) = @_;
$c->log->debug ( 'begin in Foo::Bar' );
}
sub auto :Private {
my ( $self, $c ) = @_;
$c->log->debug ( 'auto in Foo::Bar' );
}
組み込みサーバを起動して、Webブラウザで次のURLを表示させてみてください。
http://<ホスト名またはIPアドレス><:Port>/hello
このときの組み込みサーバのコンソールには次のようなログが表示されていることと思います。
[info] *** Request 1 (0.200/s) [10894] [] *** [debug] "GET" request for "hello" from "192.168.123.XXX" [debug] Path is "hello" [debug] begin in Root [debug] auto in Root [info] Request took 0.023507s (42.541/s) .------------------------------------------------------------+-----------. | Action | Time | +------------------------------------------------------------+-----------+ | /begin | 0.000390s | | /auto | 0.000102s | | /hello | 0.000163s | | /end | 0.000551s | '------------------------------------------------------------+-----------'
まず最初にRootコントローラのbeginアクションが、次いでautoアクション、その後にURLで指定したhelloアクションが実行され、最後にendアクションが実行されています。
次に、Foo::Barコントローラのhelloアクションを実行してみましょう。
http://<ホスト名またはIPアドレス><:Port>/foo/bar/hello
[info] *** Request 3 (0.250/s) [10894] [] *** [debug] "GET" request for "foo/bar/hello" from "192.168.123.XXX" [debug] Path is "foo/bar/hello" [debug] begin in Foo::Bar [debug] auto in Root [debug] auto in Foo::Bar [info] Request took 0.004783s (209.074/s) .------------------------------------------------------------+-----------. | Action | Time | +------------------------------------------------------------+-----------+ | /foo/bar/begin | 0.000250s | | /auto | 0.000131s | | /foo/bar/auto | 0.000078s | | /foo/bar/hello | 0.000088s | | /end | 0.000199s | '------------------------------------------------------------+-----------'
Foo::Barコントローラにもbeginアクションを定義しているため、Rootコントローラのbeginアクションを上書きしています。また、Rootコントローラのautoアクションの後にFoo::Barコントローラのautoアクションが実行されています。
まとめ
本記事ではコントローラについて、アクション定義に必要なアトリビュートと組み込みアクションについて説明しました。Catalystでは、URLパスとアクションを結びつけるさまざまな方法が用意されていることがご理解いただけたと思います。
次回はURLパスについての補足と、リクエストパラメータの扱い、などについて説明する予定です。
参考文献
- 『Catalyst-Manual-5.8000』
- 『モダンPerl入門』 牧大輔 著、翔泳社、2009年2月
