How to create two parent controllers in Codeignite

2019-02-28 01:19发布

I want to create two parent controllers: one for admin and one for user site. They have to extend a regular Controller class but each of them has to do different things.

2条回答
Fickle 薄情
2楼-- · 2019-02-28 01:38

This is pretty easy. Do the following:

  1. Go to the following directory: your_ci_app/application/core/ and create a php file called MY_Controller.php (this file will be where your top parent classes will reside)
  2. Open MY_Controller.php and add your multiple classes, like so:

    class Admin_Parent extends CI_Controller {
        public function __construct() {
            parent::__construct();
        }
    
        public function test() {
            var_dump("from Admin_Parent");
        }
    }
    
    class User_Parent extends CI_Controller {
    
        public function __construct() {
            parent::__construct();
        }
    
        public function test(){
            var_dump("from User_Parent");
        }
    
    }
    
  3. Create your children controllers under this directory your_ci_app/application/controllers/ . I will call it adminchild.php

  4. Open adminchild.php and create your controller code, make sure to extend the name of the parent class, like so:

    class Adminchild extends Admin_Parent {
    
        function __construct() {
            parent::__construct();
        }
    
        function test() {
            parent::test();
        }
    
    }
    
查看更多
The star\"
3楼-- · 2019-02-28 01:45

I wrote up an article showing how you do this.

http://philsturgeon.co.uk/news/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY

You need to create an __autoload() function in your config.php or directly include the base controller above the class definition.

查看更多
登录 后发表回答