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

时间:2009-05-11 19:49:15

标签: php codeigniter http-status-code-404

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

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

  1. 创建header("Location: /path/to/error_page")调用以重定向到现有(或特殊)控制器的404处理程序
  2. 添加某种默认路由器来处理它。
  3. 达到所需结果的最佳方法是什么?是否有任何陷阱需要注意?

1 个答案:

答案 0 :(得分: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;
}

在控制器中,我可以这样做:

$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();
}

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

$CI =& get_instance();
$CI->cismarty->not_found();

效果很好,使用少量代码,并且不会为不同类型的缺失实体复制404功能。

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

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

Using Smarty with CodeIgniter