我使用Codeigniter 3,我想自定义show_404()函数。
这是我的主控制器:
class Welcome extends CI_Controller {
public function index() {
$this->load->view('welcome_message');
}
public function otherMethod() {
show_404();
}
}
添加到我的routes.php
$route['404_override'] = 'error/show_404_custom';
用show_404_custom方法创建控制器Error.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Error extends CI_Controller {
public function show_404_custom() {
$this->load->view('404_read_view');
}
}
404_read_view.php视图:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Custom 404 page.</p>
</body>
</html>
然后我测试了一些未定义的URL,如:
/index.php/welcome/method_A
我成功地得到了我的自定义404页面。
但是,如果我运行一个使用show_404()
函数的方法,如:
/index.php/welcome/otherMethod
我奇怪地得到了标准的Codeigniter 404页面。
我搜索了一下,发现我应该扩展Exception核心类,并像这样覆盖show_404()函数:
https://stackoverflow.com/a/8425433/4301970
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
class MY_Exceptions extends CI_Exceptions {
public function __construct() {
parent::__construct();
}
public function show_404() {
$CI =& get_instance();
$CI->load->view('404_read_view');
echo $CI->output->get_output();
exit;
}
}
当我运行URL:
/index.php/welcome/otherMethod
我得到错误:
Fatal error: Class 'MY_Exceptions' not found in (...)'system'core'Common.php on line 196
我看了看Common.php,注意到load类函数在库目录而不是核心目录?
function &load_class($class, $directory = 'libraries', $param = NULL)
我该如何解决这个问题?
使用这个,它的工作在CI 3.1.4(我的最新项目)
class MY_Exceptions extends CI_Exceptions {
public function __construct()
{
parent::__construct();
}
function show_404($page = '', $log_error = TRUE)
{
$CI =& get_instance();
$CI->load->view('404_read_view');
echo $CI->output->get_output();
exit;
}
}
当您需要使用CI3时,404_override不能在子文件夹
改变$route['404_override'] = 'error/show_404_custom';
// thinks its in subfolder
Location: application> controllers> Error.php
$route['404_override'] = 'error';
控制器<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Error extends CI_Controller {
public function index() { // change to index
$this->load->view('404_read_view');
}
}