我正在使用 CodeignIter,并且正在寻找一种在调用方法不存在时为单个控制器编写自定义处理例程的方法。
假设你打电话www.website.com/components/login
在components
控制器中,没有一个名为 的方法login
,因此它不会发送 404 错误,而是默认使用另一个名为 的方法default
。
我正在使用 CodeignIter,并且正在寻找一种在调用方法不存在时为单个控制器编写自定义处理例程的方法。
假设你打电话www.website.com/components/login
在components
控制器中,没有一个名为 的方法login
,因此它不会发送 404 错误,而是默认使用另一个名为 的方法default
。
是的,有一个解决方案。如果您有Components
控制器和文件名components.php
。编写以下代码...
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Components extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function _remap($method, $params = array())
{
if (method_exists(__CLASS__, $method)) {
$this->$method($params);
} else {
$this->test_default();
}
}
// this method is exists
public function test_method()
{
echo "Yes, I am exists.";
}
// this method is exists
public function test_another($param1 = '', $param2 = '')
{
echo "Yes, I am with " . $param1 . " " . $param2;
}
// not exists - when you call /compontents/login
public function test_default()
{
echo "Oh!!!, NO i am not exists.";
}
}
由于default
PHP 是保留的,因此您不能使用它,因此您可以像这里一样编写自己的默认方法test_default
。这将自动检查您的类中是否存在方法并相应地重定向。它还支持参数。这对我来说很完美。你可以自己测试一下。谢谢!!