Codeigniter 3 autoload controller Codeigniter 3 autoload controller codeigniter codeigniter

Codeigniter 3 autoload controller


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:

  1. Move REST_Controller.php into directory YourProject/application/core/.
  2. 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


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/' locationclass 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 controllerclass 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>';    }}