ログ出力用のアクションヘルパー | Inhale n’ Exhaleどんなアプリケーションを開発するときでも、簡単にログを出力できる仕組みは早いうちに実装しておきたいものだ。Zend Frameworkでログ出力をするときはZend_Logを利用するのが一般的。サンプルコードを見ると、
1 | $writer = new Zend_Log_Writer_Stream( 'php://output' ); |
2 | $logger = new Zend_Log( $writer ); |
と、ライターのインスタンスを生成してロガーのインスタンスを生成するコードを書くのか?と思わされるが、幸いZend_Application_Resource_Logというリソースプラグインが用意されているので、
1 | resources.log.stream.writerName = "Stream" |
2 | resources.log.stream.writerParams.stream = "php://output" |
のような設定ファイルを作れば、ブートストラップからZend_Logのインスタンスを取得できるようになる。`zf create project`
コマンドで作られるデフォルトのエラーコントローラには、ブートストラップを利用してログを出力するコードが含まれている。
1 | class ErrorController extends Zend_Controller_Action |
3 | public function errorAction() |
8 | if ( $log = $this ->getLog()) { |
9 | $log ->crit( $this ->view->message, $errors ->exception); |
15 | public function getLog() |
17 | $bootstrap = $this ->getInvokeArg( 'bootstrap' ); |
18 | if (! $bootstrap ->hasResource( 'Log' )) { |
21 | $log = $bootstrap ->getResource( 'Log' ); |
エラーコントローラでだけでなく、自前のアクションコントローラでも同じようにログ出力を行いたいと思ったときに、上記のような実装をいちいち書かなければならないのは非常に面倒なので、こういう場合はアクションヘルパーを作ってしまうのが一番。
1 | class My_Action_Helper_Log extends Zend_Controller_Action_Helper_Abstract |
3 | public function direct() |
5 | call_user_func_array( array ( $this , 'info' ), func_get_args()); |
8 | public function __call( $method , $params ) |
10 | $logger = $this ->_getLogger(); |
13 | call_user_func_array( array ( $logger , $method ), $params ); |
17 | private function _getLogger() |
19 | $bootstrap = $this ->getActionController()->getInvokeArg( 'bootstrap' ); |
20 | return $bootstrap ->hasResource( 'Log' ) ? $bootstrap ->getResource( 'Log' ) : false; |
マジックメソッド__call()
を使うことで、Zend_Logが持っている関数すべてにアクセスできるようにしている。プロキシクラスね。_getLogger()
関数は、前述のエラーコントローラーのgetLog()
関数の実装をパクった。アクションコントローラなのでdirect()
を実装して、ここではとりまZend_Log::INFO
でログ出力するようにしたが、アプリケーションの中で最も頻繁に使われるプライオリティを実装しておくといいだろう。
前述のエラーコントローラでのログ出力部分が
2 | $this ->_helper->log->crit( $this ->view->message, $errors ->exception); |
と、呼び出せるようになる。
1 コメント