CodeIgniter Extending Multiple Controllers?

痞子三分冷 提交于 2019-11-30 07:22:11

Assuming that you are using Codeigniter 2, this can be done by putting all you extended controller classes in the same file.

In /application/core create a file called MY_Controller.php (don't forget to check the subclass prefix in config.php around line 109)

In here you can add all you controller classes to extend. For example;

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * MY_Controller Class
 *
 *
 * @package Project Name
 * @subpackage  Controllers
 */
class MY_Controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->form_validation->set_error_delimiters('<div class="form-error">', '</div>');
    }
}

class LoggedIn extends MY_Controller {

    public function __construct() {
        parent::__construct();
        if (is_logged_in() == FALSE) {
            $this->session->set_userdata('return_to', uri_string());
            $this->session->set_flashdata('message', 'You need to log in.');
            redirect('/home');
        }
    }
}

class AdminLayout extends LoggedIn {

    public function __construct() {
        parent::__construct();
        // do something
    }
}

class ModLayout extends LoggedIn {

    public function __construct() {
        parent::__construct();
        // do something
    }
}

/* End of file  */
/* Location: ./application/core/ */

Then when you create your controllers as per normal, just choose the base controller class to extend. Example;

class Foo extends AdminLayout {

    public function __construct() {
        parent::__construct();
        if (is_logged_in() == FALSE) {
            $this->session->set_userdata('return_to', uri_string());
            $this->session->set_flashdata('message', 'You need to log in.');
            redirect('/home');
        }
    }
}

or

class Bar extends ModLayout {

    public function __construct() {
        parent::__construct();
        if (is_logged_in() == FALSE) {
            $this->session->set_userdata('return_to', uri_string());
            $this->session->set_flashdata('message', 'You need to log in.');
            redirect('/home');
        }
    }
}

PHP does not support multiple inheritance. You could use Codeigniter helpers or libraries for this.

Have a look at the library examples:

http://codeigniter.com/wiki/Simplelogin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!