问题
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';
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.
Thank in advance
回答1:
You can achieve this through Codeigniter
's autoload configuration.
Edit your project's autoload.php
which is located in directory YourProject/application/config/
$autoload['libraries'] = array('REST_Controller');
And in controllers access this library class through $this->rest_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
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.
Solution:
- 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_';
then Codeigniter
will load REST_Controller
automatically.
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.
Notice: MY_Controller
need extending from CI_Controller
回答2:
Put file include in constructor of MY_Controller
class, then extend it to any controller that needs to use REST_Controller
.
If you don't have MY_Controller.php
file in APPPATH.'core/'
location, make one and use it as presented here:
<?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
}
}
Now, in every controller you want to use REST_Controller have code like this:
<?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>';
}
}
来源:https://stackoverflow.com/questions/38866474/codeigniter-3-autoload-controller