8

我在codeigniter中使用REST Server,使用方法是,然后在我所有控制器的应用程序中,我必须在开始时写下这一行:

require APPPATH . '/libraries/REST_Controller.php';

有谁知道如何自动加载这个 REST_Controller 并在我的所有控制器中避免这条线?我不想使用要求。

预先感谢

4

2 回答 2

6

Codeigniter您可以通过的自动加载配置来实现这一点。

编辑autoload.php位于目录中的项目YourProject/application/config/

$autoload['libraries'] = array('REST_Controller');

并且在控制器中通过$this->rest_controller.

BTW:Rest_Controllers 是一个库文件,所以我认为后缀的名称不是Controller一个好名字。

编辑

通过您的评论,我了解到您实际上是指所有控制器都从 扩展REST_Controller,并且您不希望在每个控制器文件的顶部都需要它。

解决方案:

  1. 移入REST_Controller.php目录YourProject/application/core/
  2. YourProject/application/config/config.php第 119 行更改$config['subclass_prefix'] = 'MY_';$config['subclass_prefix'] = 'REST_';

然后Codeigniter会自动加载REST_Controller

但是subclass_prefix配置具有全局效果,并且您需要更改 的位置REST_Conttoller.php,因此为了进行最小的更改,我认为最好的方法是MY_Controller在目录中创建类并在这个新文件的底部添加./application/core/require 。REST_Controller何时也需要自动CI加载。MY_controllerREST_Controller

注意: MY_Controller需要从CI_Controller

于 2016-08-10T07:26:57.267 回答
3

将文件包含在MY_Controller类的构造函数中,然后将其扩展到需要使用的任何控制器REST_Controller。如果您的位置没有MY_Controller.php文件APPPATH.'core/',请制作一个并按照此处所示使用它:

<?php defined('BASEPATH') OR exit('See you next time.');

//APPPATH.'core/' location
class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        require APPPATH . 'libraries/REST_Controller.php';//this constant ends with slash already
    }
}

现在,在你想使用 REST_Controller 的每个控制器中都有这样的代码:

<?php defined('BASEPATH') OR exit('See you next time.');

//example controller
class Api extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    //bare example method
    public function some_get()
    {
        echo '<pre>', var_dump('Some REST_Controller code logic here'), '</pre>';
    }
}
于 2016-08-10T08:05:50.923 回答