Codeigniter 3自动加载控制器 [英] Codeigniter 3 autoload controller
问题描述
我在codeigniter中使用 REST Server ,使用方法是我所有控制器中的应用程序,我必须在开始时写以下行:
I'm using REST Server in codeigniter, and the way to use is that then in my app in all my controllers I must write this line on start:
require APPPATH . '/libraries/REST_Controller.php';
有人知道如何自动加载此REST_Controller并避免在我的所有控制器中使用此行吗?我不想使用require.
Does anyone know how to autoload this REST_Controller and to avoid this line in all my controllers? I don't want to use require.
预先感谢
推荐答案
您可以通过Codeigniter
的自动加载配置来实现.
You can achieve this through Codeigniter
's autoload configuration.
编辑位于目录YourProject/application/config/
$autoload['libraries'] = array('REST_Controller');
并且在控制器中,可以通过$this->rest_controller
访问此库类.
And in controllers access this library class through $this->rest_controller
.
顺便说一句:Rest_Controllers是一个库文件,所以我认为后缀Controller
的名称不是很好的名字.
BTW: Rest_Controllers is a library file, so I don't think a name suffixed with Controller
is a good name for it.
编辑
Edit
通过您的评论,我得到的是您实际上是指所有从REST_Controller
扩展的控制器,并且您不想在每个控制器文件的顶部都要求它.
Through your comment I got that you actually mean all of your controllers extended from REST_Controller
, and you don't want require it at the top of every controller file.
解决方案:
- 将
REST_Controller.php
移至目录YourProject/application/core/
. - 在
YourProject/application/config/config.php
行119中将$config['subclass_prefix'] = 'MY_';
更改为$config['subclass_prefix'] = 'REST_';
- Move
REST_Controller.php
into directoryYourProject/application/core/
. - In
YourProject/application/config/config.php
line 119 change$config['subclass_prefix'] = 'MY_';
to$config['subclass_prefix'] = 'REST_';
然后Codeigniter
将自动加载REST_Controller
.
但是subclass_prefix
配置具有全局作用,您需要更改REST_Conttoller.php
的位置,因此要进行最小的更改,我认为最好的方法是在目录./application/core/
中创建MY_Controller
类并要求REST_Controller
在此新文件的底部.当CI
自动加载MY_controller
时,也将需要REST_Controller
.
But the subclass_prefix
config has a global effect, and you need change the location of REST_Conttoller.php
, so to make minimal change I think the best way is you create MY_Controller
class in directory ./application/core/
and require REST_Controller
at bottom of this new file. When CI
load MY_controller
automatically REST_Controller
will be required too.
通知: MY_Controller
需要从CI_Controller
这篇关于Codeigniter 3自动加载控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!