问题描述
我正在使用CodeignIter,并在不存在被调用方法的情况下寻找一种为单个控制器编写自定义处理例程的方法.
I am using CodeignIter and am looking to for a way to write a custom handling routine for a single controller when a called method does not exist.
假设您致电www.website.com/components/login
在components
控制器中,没有名为login
的方法,因此,它不会发送404错误,而是简单地默认为另一个名为default
的方法.
In the components
controller, there is not a method called login
, so instead of sending a 404 error, it would simply default to another method called default
.
推荐答案
是的,有解决方案.如果您具有Components
控制器和文件名components.php
.编写以下代码...
Yes there is a solution. If you have Components
controller and the flilename components.php
. Write following code...
<?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
.这将自动检查类中是否存在method并相应地重定向.它还支持参数.这完全适合我.您可以测试自己.谢谢!
Since default
is PHP reserved you cannot use it so instead you can write your own default method like here test_default
. This will automatically checks if method exists in your class and redirect accordingly. It also support parameters. This work perfectly for me. You can test yourself. Thanks!!
这篇关于如果CodeIgniter方法不存在,则重定向到默认方法.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!