CodeIgniter extends multiple controllers?

It is impossible to find a way to do this, perhaps because there is another way to do this?

Some of my controllers extend AdminLayout, and some of them extend ModLayout, but I also need these pages to extend the LoggedIn Controller.

class Profile extends AdminLayout, LoggedIn { 

However, looking into it, there is no way to make it beautiful. Is there any workaround?

+7
source share
2 answers

Assuming you are using Codeigniter 2, you can do this by placing all the extended controller classes in the same file.

In / application / core, create a file called MY_Controller.php (remember to check the subclass prefix in config.php around line 109)

Here you can add all controller classes for expansion. 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 in normal mode, simply select 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'); } } } 
+25
source

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

Check out the sample libraries:

http://codeigniter.com/wiki/Simplelogin

+2
source

All Articles