【问题标题】:SilverStripe framework only - how to handle 404仅限 SilverStripe 框架 - 如何处理 404
【发布时间】:2014-09-15 23:55:52
【问题描述】:

我第一次只使用没有 CMS 模块的框架。当我通过控制器/操作未处理的 URL 访问应用程序时,我只得到一个带有文本“没有匹配 URL 规则”的页面。这是由于 Director::handleRequest() 没有将任何控制器与 url 段匹配...或者“操作 'ABC' 在类 XYZController 上不可用。”

我想将任何未处理的请求定向到一个控制器,该控制器相当于一个漂亮的 404 页面。这样做的正确或最佳方法是什么?

【问题讨论】:

    标签: silverstripe


    【解决方案1】:

    错误模板仅包含在 CMS 中。该框架只返回带有纯文本消息的 HTTP 响应代码。

    我也刚刚开始了自己的纯框架项目,这是我的解决方案:

    [routes.yml]

    ---
    Name: rootroutes
    ---
    Director:
      rules:
        '': 'MyController'
        '$URLSegment': 'MyController'
    

    [我的控制器]

    class MyController extends Controller {
    
        private static $url_handlers = array(
            '$URLSegment' => 'handleAction',
        );
    
    
        public function index() {
            return $this->httpError(404, "Not Found");
        }
    
    
        /**
         * Creates custom error pages. This will look for a template with the 
         * name ErrorPage_$code (ie ErrorPage_404) or fall back to "ErrorPage".
         *
         * @param $code int
         * @param $message string
         *
         * @return SS_HTTPResponse
        **/
        public function httpError($code, $message = null) {
            // Check for theme with related error code template.
            if(SSViewer::hasTemplate("ErrorPage_" . $code)) {
                $this->template = "ErrorPage_" . $code;
            } else if(SSViewer::hasTemplate("ErrorPage")) {
                $this->template = "ErrorPage";
            }
    
            if($this->template) {
                $this->response->setBody($this->render(array(
                    "Code" => $code,
                    "Message" => $message,
                )));
                $message =& $this->response;
            }
    
            return parent::httpError($code, $message);
        }
    
    }
    

    [ErrorPage.ss]

    <h1>$Code</h1>
    <p>$Message</p>
    

    您还可以使用 ErrorPage_404.ss、ErrorPage_500.ss 等创建更具体的错误模板。

    【讨论】:

    • 对不起,我应该补充一点,这只是一个基本示例。在您自己的应用程序中,您需要以不同的方式进行路由,并且 404 很可能会在 handleAction 或 handleRequest 中抛出。
    【解决方案2】:

    如果不更新前面提到的路由,我最近一直在研究一个模块,它允许正则表达式重定向映射,挂钩到未找到的页面 (404)。这已被设计为在有或没有 CMS 存在的情况下运行:)

    https://github.com/nglasl/silverstripe-misdirection

    它基本上利用请求过滤器来处理当前请求/响应,适当地引导您处理可能已定义的任何映射。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-25
      • 2015-01-28
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-12
      相关资源
      最近更新 更多