How to extend CI_Controller to more than one core?

1

In Codeigniter you can create a MY_Controller.php file in the application / core folder and the extended controller of that file, a basic example would be:

<?php
class MY_Controller extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        $this->load->helper('url');
    }

}

What I need is to create other files in this core by extending the CI_Controller itself, such as MY_Admincontroller.php and it would have another modeling for MY_Controller, for example:

<?php
class MY_Admincontroller extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        $this->load->helper('admin');
    }

}

Except that doing this gives me an error that did not find the MY_Admincontroller.

Fatal error: Class 'MY_Admincontroller' not found in ...

I know that it is possible for me to create this MY_Admincontroller just below the MY_Controller, in the same file and so, but with that the code will be much more polluted. Does anyone know if it's possible to do what I'm looking for?

A form that gives to do, well summarized, but as I said, the code itself gets very polluted and with that difficult maintenance

<?php
class MY_Controller extends CI_Controller {}

class MY_Admincontroller extends MY_Controller {}

class MY_Othercontroller extends MY_Admincontroller {}
    
asked by anonymous 16.07.2016 / 15:58

1 answer

1

You can do this simply by including the base controller file as below when you are going to use it:

include_once(APPPATH.'core/Nome_Controller.php');

For example:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

include_once(APPPATH.'core/Admin_Controller.php');

class MySite extends Admin_Controller {

    public function index()
    {
        $this->load->view('my_site');
    }

}

Another way, even more usual, would be to use autoload, where you do not have to do include in all your controllers of the base controller file. As follows:

At the end of the file application/config/config.php or anywhere in it, include this autoload load_my_controllers function:

functionload_my_controllers($class){$path=APPPATH.'core/'.$class.'.php';if(strpos($class,'CI_')!==0&&is_readable($path)){require_once($path);}}spl_autoload_register('load_my_controllers');

Onceyouhavedonethis,youcannowincludemorethanonebasecontrollerinthecorefolderofyourapplication.

    
17.07.2016 / 05:16