Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

php - CodeIgniter 2: How to extend CI_Controller multiple times?

I have successfully extended the CI_Controller class by creating a MY_Controller.php which I have placed in the application/core directory.

core/My_Controller.php looks something like this:

class MY_Controller extends CI_Controller {

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

Then when I create normal controllers they look something like this:

class Home extends MY_Controller {

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

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

I'm creating a admin back end and I want to have a different base class for controllers to extend instead of My_Controller. This is so I can have common methods for the admin controllers (i.e. authentication_check etc.)

What I can't work out is how I create another controller that extends CI_Controller.

The goal is for admin controllers to extend a different base class than the front-end controllers.

The admin base controller would look like this:

class MY_Admin_Controller extends CI_Controller {

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

An normal controller for admin pages:

class Admin_home extends MY_Admin_Controller {

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

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

The problem is that to extend the CI_Controller class you must name your controller file PREFIX_Controller.php and place it in the core/ directory. But I want two controller classes and they can't have the same filename.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just put both in the same file, I have a project that is exactly the same as this.

We just have both the admin and normal extended controller in the MY_Controller.php file, works fine.

The main reason for the MY_Controller or other extended files is so that CodeIgniter auto initiates them when you load the base file (whether library, helper, etc.), you can have many classes in these files.

Edit:

You don't even need to call them MY_Admin_Controller or MY_Controller, we have Admin_Controller and User_Controller and Ajax_Controller in the MY_Controller File


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...