LoginSignup
1
0

More than 5 years have passed since last update.

MissingViewExceptionのときにHTTPステータスコード404を返す

Last updated at Posted at 2016-08-31

必要環境

  • CakePHP 2.x

何をするの?

以下のような routes.php の形でリクエストを PagesController で一挙に引き受けたい場合があるとします(本来は1つづつ Router に追加していくものだと思います)。

Config/routes.php
Router::connect('*', array('controller' => 'pages', 'action' => 'display'));

ただ、このような形だと View の該当ファイルが存在しない場合、MissingViewException が発生し、HTTPステータスコード 500 として扱われます。
これを 404 として扱うよう変更します。

それでは変更

View#_getViewFileName() で扱う View を決定し、なければ MissingViewException が投げられます。
なので、ここを変更すればおkですね。

Config/bootstrap.php
/**
 * Used when a view file cannot be found on PagesController#display().
 *
 * @package       Cake.Error
 */
class MyMissingViewException extends CakeException {

    protected $_messageTemplate = 'View file "%s" is missing.';

//@codingStandardsIgnoreStart
    public function __construct($message, $code = 404) {
        parent::__construct($message, $code);
    }
//@codingStandardsIgnoreEnd

}
View/MyView.php
<?php
App::uses('View', 'View');

/**
 * MyView
 *
 */
class MyView extends View {

/**
 * Returns filename of given action's template file (.ctp) as a string.
 * CamelCased action names will be under_scored! This means that you can have
 * LongActionNames that refer to long_action_names.ctp views.
 *
 * @param string $name Controller action to find template filename for
 * @return string Template filename
 * @throws MyMissingViewException when a view file could not be found.
 */
    public function _getViewFileName($name = null) {
        try {
            return parent::_getViewFileName($name);
        } catch (MissingViewException $e) {
            throw new MyMissingViewException(array('file' => $name . $this->ext));
        }
    }
}
Controller/PagesController.php
/**
 * Displays a view
 *
 * @param mixed What page to display
 * @return void
 */
    public function display() {
        $this->viewClass = 'My';

        // Do something
    }

以上、小ネタでした!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0