如何为CodeIgniter创建一个像样的错误404处理程序?

Mar*_*ton 5 php codeigniter http-status-code-404

CodeIgniter有/system/application/errors/error_404.php,当有404因为实际上是"未找到控制器"条件时显示.但是,对于我的项目,我真的需要处理这个错误就像控制器类中缺少方法一样.在这种情况下,我显示一个普通的视图,其中包含一个漂亮的"未找到页面:也许你的意思是这个?..."页面,其中包含数据库生成的导航等.

我的想法是我可以做两件事之一:

  1. 创建一个header("Location: /path/to/error_page")调用以重定向到现有(或特殊)控制器的404处理程序
  2. 添加某种默认路由器来处理它.

达到要求结果的最佳方法是什么?是否有任何陷阱需要注意?

Glo*_*ish 2

我将 CodeIgniter 与 Smarty 一起使用。我的 Smarty 类中有一个名为 notfound() 的附加函数。调用 notfound() 将正确的标头位置设置为 404 页面,然后显示 404 模板。该模板具有可覆盖的标题和消息,因此用途非常广泛。这是一些示例代码:

Smarty.class.php

function not_found() {
header('HTTP/1.1 404 Not Found');

if (!$this->get_template_vars('page_title')) {
    $this->assign('page_title', 'Page not found');
    }

    $this->display('not-found.tpl');
    exit;
}
Run Code Online (Sandbox Code Playgroud)

在控制器中我可以做这样的事情:

$this->load->model('article_model');
$article = $this->article_model->get_latest();

if ($article) {
    $this->smarty->assign('article', $article);
    $this->smarty->view('article');
} else {
    $this->smarty->assign('title', Article not found');
    $this->smarty->not_found();
}
Run Code Online (Sandbox Code Playgroud)

同样,我可以将 /system/application/error/error_404.php 中的代码更改为:

$CI =& get_instance();
$CI->cismarty->not_found();
Run Code Online (Sandbox Code Playgroud)

它运行良好,使用少量代码,并且不会针对不同类型的缺失实体重复 404 功能。

我认为您可以使用内置的 CodeIgniter 视图执行类似的操作。重要的是在进行视图操作之前吐出标题。

更新:我使用类似于此处描述的自定义 Smarty 包装器:

将 Smarty 与 CodeIgniter 结合使用