How to create a decent 404 error handler for CodeIgniter?

CodeIgniter has / system / application / errors / error _404.php, which is displayed when there is 404 due to what is actually a "controller not found". However, for my project, I really need this error to be handled exactly the same as when there is no class in the controller class. In this case, I am showing a normal view with a beautiful page not found: Perhaps you meant this? ... page with navigation created using a database, etc.

My thoughts are that I could do one of two things:

  • Create a call header("Location: /path/to/error_page")to redirect to an existing (or special) 404 controller
  • Add some default router to it.

What is the best way to achieve the desired result? Are there any pitfalls to watch out for?

+5
source share
1 answer

I am using CodeIgniter with Smarty. I have an extra function in the Smarty class called notfound (). A call to notfound () sets the header to the correct location on page 404, and then displays the 404 template. The template has a redefined header and message, so it is very versatile. Here is a sample code:

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;
}

In the controller, I can do something like this:

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

Similarly, I can change the code in / system / application / error / error _404.php to:

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

It works great, uses a little code and does not duplicate 404 functionality for different types of missing objects.

, CodeIgniter. , , .

: Smarty, , :

Smarty CodeIgniter

+2

All Articles