僕はcakeErrorでbeforeFilterが使いたいんです。

Twitter ツイート Hatena Bookmark ブックマーク

cakePHP使っているとエラー処理のためにcakeErrorを使うことが多いかと思います。
でもbeforeFilterが実行されないですね。。
普段はまあいいんですが、KtaiLibraryとか使ってしまっている場合は結構不便ですよね。。。

コードみたら、beforeFilterが実行されていなかったのね。。。
最初はAppErrorクラス作成してコンストラクタ継承してparent::__constractした後にbeforeFilterしてしまえとか思って以下のように書いてみました。

1
2
3
4
5
6
7
8
9
<?php
class AppError extends ErrorHandler
{
	function __construct($method, $messages) {
		parent::__construct($method,$message);
		$this->controller->beforeFilter();
	}
}
?>

ところがどっこい、この方法だと意味がないことに気づきました。。
なんとかする方法ないかなーと考えてましたが、結局コンストラクタ書き換えるしかないのね。

つーことこでこんな感じで$this->controller->beforeFilter()を加えて見ました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
class AppError extends ErrorHandler
{
	function __construct($method, $messages) {
		App::import('Core', 'Sanitize');
		static $__previousError = null;

		if ($__previousError != array($method, $messages)) {
			$__previousError = array($method, $messages);
			$this->controller =& new CakeErrorController();
		} else {
			$this->controller =& new AppController();
			$this->controller->viewPath = 'errors';
		}

		$this->controller->beforeFilter();

		$options = array('escape' => false);
		$messages = Sanitize::clean($messages, $options);

		if (!isset($messages[0])) {
			$messages = array($messages);
		}

		if (method_exists($this->controller, 'apperror')) {
			return $this->controller->appError($method, $messages);
		}

		if (!in_array(strtolower($method), array_map('strtolower', get_class_methods($this)))) {
			$method = 'error';
		}

		if ($method !== 'error') {
			if (Configure::read('debug') == 0) {
				$parentClass = get_parent_class($this);
				if (strtolower($parentClass) != 'errorhandler') {
					$method = 'error404';
				}
				$parentMethods = array_map('strtolower', get_class_methods($parentClass));
				if (in_array(strtolower($method), $parentMethods)) {
					$method = 'error404';
				}
				if (isset($messages[0]['code']) && $messages[0]['code'] == 500) {
					$method = 'error500';
				}
			}
		}
		$this->dispatchMethod($method, $messages);
		$this->_stop();

	}


}

コードは長く見えますがただ、16行目に $this->controller->beforeFilter();を加えただけですw

こうすることで無事beforeFilterが実行されます。

comments powered by Disqus
Built with Hugo
テーマ StackJimmy によって設計されています。