Quantcast
Channel: HAPPY*TRAP » CakePHP
Viewing all articles
Browse latest Browse all 10

[CakePHP] 例外時のレイアウトファイル変更

$
0
0
[CakePHP] cronからの実行

CakePHPで例外時のレイアウトファイルを変更する方法です。

やり方はいろいろあると思いますが、今回は、ExceptionRendererクラスのサブクラスAppExceptionRendererを新規に作成して、_outputMessage()をオーバーライドする方法でやってみます。

app/Lib/Error/AppExceptionRenderer.php
1
2
3
4
5
6
7
8
9
<?php
App::uses('ExceptionRenderer', 'Error');
class AppExceptionRenderer extends ExceptionRenderer {
    protected function _outputMessage($template) {
        // ここでレイアウトファイルを指定
        $this->controller->layout = 'custom';
        parent::_outputMessage($template);
    }
}

作成したAppExceptionRendererクラスを例外時のrendererに指定します。

app/Config/core.php
1
2
3
4
5
Configure::write('Exception', array(
    'handler' => 'ErrorHandler::handleException',
    'renderer' => 'AppExceptionRenderer', // ここを変更
    'log' => true
));

準備完了です。試しに、例外を投げてみましょう。

app/Controller/ExamplesController.php
1
2
3
public function view () {
    throw new NotFoundException('Could not find that post');
}

指定したレイアウトファイルは表示されたでしょうか?

上記の例では、例外によらず一律にレイアウトファイルを変更しましたが、例外毎に振り分けたい場合は、_outputMessage()の引数を利用したり、ExceptionRendererクラスの各メソッド(error400()など)をオーバーライドするなどで実現できそうです。


(参考) Exceptions — Cookbook v2.x documentation

環境
PHP 5.3.10
CakePHP 2.1.0

Viewing all articles
Browse latest Browse all 10

Trending Articles