由於催化劑以駝鹿和Catalyst ::控制器對象是穆斯objec你可以使用Moose角色。
package Hello::DebugRole;
use Moose::Role;
use MooseX::MethodAttributes::Role;
sub auto :Private {
my ($self, $c) = @_;
$c->log->debug('Hello!');
return 1;
}
1;
我們需要MooseX::MethodAttributes::Role來啓用CODE屬性。如果沒有,它會在執行時死掉,如果我們省略了:Private
,Catalyst不會將其視爲操作,而是將其視爲本地方法。
這種方法很有意義,因爲您可以在一個地方定義您的auto
操作,這非常乾燥,並且您可以在需要的地方完全重複使用該代碼。
現在你可以在你想要的所有控制器中使用它。只要把它放在BEGIN
區塊。
package Hello::Controller::User;
use Moose;
use namespace::autoclean;
BEGIN { extends 'Catalyst::Controller'; with 'Hello::DebugRole'; }
如果我瀏覽到該控制器,該日誌將是這樣的:
[debug] Path is "user"
[debug] "GET" request for "user/" from "127.0.0.1"
[debug] Hello!
[debug] Response Code: 200; Content-Type: text/html; charset=utf-8; Content-Length: unknown
[info] Request took 0.010909s (91.667/s)
.------------------------------------------------------------+-----------.
| Action | Time |
+------------------------------------------------------------+-----------+
| /user/auto | 0.000237s |
| /user/index | 0.000152s |
| /end | 0.000394s |
'------------------------------------------------------------+-----------'
[info] *** Request 2 (0.286/s) [24045] [Wed Jan 6 16:16:15 2016] ***
但是,如果我定位到Foobar的控制器來代替,沒有自動的動作,也沒有您好!。
[info] *** Request 3 (0.250/s) [24045] [Wed Jan 6 16:16:20 2016] ***
[debug] Path is "foobar"
[debug] "GET" request for "foobar/" from "127.0.0.1"
[debug] Response Code: 200; Content-Type: text/html; charset=utf-8; Content-Length: unknown
[info] Request took 0.007135s (140.154/s)
.------------------------------------------------------------+-----------.
| Action | Time |
+------------------------------------------------------------+-----------+
| /foobar/index | 0.000181s |
| /end | 0.000179s |
'------------------------------------------------------------+-----------'
注意,催化劑將調用所涉及的所有控制器的auto
動作,所以它也將做根控制器的auto
如果有一個在所有請求。
有趣的是,我在寫自己的答案和研究如何將行動置於角色中時沒有看到這一點。這個出現的博客文章很好,但你的答案只是鏈接,而不是。 :) – simbabque
這是因爲我打算工作;) –