我正在使用CodeignIter,我正在寻找一种方法,当一个被调用的方法不存在时,为单个控制器编写自定义处理例程。
让我们打电话给www.website.com/components/login
在components
控制器中,没有一个名为login
的方法,因此它不会发送404错误,而是默认使用另一个名为default
的方法。
答案 0 :(得分:7)
是的,有一个解决方案。如果您有Components
控制器和flilename 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
。这将自动检查您的类中是否存在方法并相应地重定向。它还支持参数。这项工作非常适合我。你可以测试自己。谢谢!