Codeigniter - 从routes文件中检查Controller功能是否存在

时间:2016-04-07 06:40:01

标签: php codeigniter session routes

有没有办法检查路径文件中控制器中是否存在功能方法。我已尝试如下所示,但在控制器使用会话库时卡住了,我无法在路径文件中添加这些库。

$urlArr = array_values(array_filter(explode('/', $_SERVER['PATH_INFO'])));
$folderName = $urlArr[0];
$controllerName = $urlArr[1];
$actionName = !empty($urlArr[2]) ? $urlArr[2] : 'index';

include_once FCPATH."system/core/Controller.php";
include_once FCPATH."application/core/MY_Controller.php";
include_once FCPATH."application/controllers/$folderName/$controllerName.php";

// Here I need to check whether the function ($actionName) exists or not

注意:不建议将文件检查为字符串并检查函数定义字符串是否存在的解决方案。

感谢任何帮助。谢谢:))

1 个答案:

答案 0 :(得分:1)

假设您使用Test方法index控制器:

class Test extends CI_Controller
{

    public function index()
    {
        echo 'index';
    }

}

由于PHP> = 5.3,您可以使用回调代替正常的路由规则。要检查是否定义了方法,您可以使用ReflectionClass。以下是Test控制器的示例:

$route['test'] = function()
{
    require_once FCPATH."system/core/Controller.php";
    require_once APPPATH.'controllers/Test.php';
    $rc = new ReflectionClass('Test');

    var_dump($rc->hasMethod('publicFoo')); // bool(false)
    var_dump($rc->hasMethod('index')); // bool(true)

    return 'Test/index'; // return your routing
};