Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Codeigniter extends one controller into another controller

I am using codeigniter(3.1.5) and Ihave two controllers in my application/controllers/ folder. with name controller A and Controller B. I want to extends Controller A in Controller B so that I can use methods of Controller A. But it generates class not found error.

Here is my sample code:

A_Controller.php:

defined('BASEPATH') OR exit('No direct script access allowed');
class A_Controller extends CI_Controller {
  public function index()
  {
  }

  public function display(){
     echo 'base controller function called.';
  }
 }

B_Controller.php:

 defined('BASEPATH') OR exit('No direct script access allowed');
 class B_Controller extends A_Controller {

 }

I want to execute display() method of controller A in controller B. If i put controller A in application/core/ folder and in application/config/config.php file make

$config['subclass_prefix'] = 'A_';

then I can able to access methods of controller A.

Please suggest. Thanks in advance.

like image 351
Abhishek Avatar asked Oct 19 '25 12:10

Abhishek


2 Answers

Extending a controller in another controller is not really good. Building with MVC and especially with CI, you have other options to achieve this.

  1. Use a class MY_Controller inside application/core that extends the CI_Controller. Later, all (or some) of your controllers should extend the MY_Controller. In MY_Controller you can have many functions and you can call which function you want in your controller.

  2. Use a library. Write your own library in application/libraries and load it in your controller wherever you want. A library is a class with functionality for your project.

  3. Use a helper. Write your own helper in application/helpers and load it in your controller. A helper should have a general purpose for your application.

    In that way, your code will be more flexible and reusable for the future. Messing with 2 Controllers seems bad to me. Remember that with the default Routing system of CI you can be confused.

like image 199
GeorgeGeorgitsis Avatar answered Oct 21 '25 02:10

GeorgeGeorgitsis


Try to use following code.

defined('BASEPATH') OR exit('No direct script access allowed');
     class B_Controller extends A_Controller {
        public function test()
        {
            $this->display();
        }
     }
like image 23
B2725 Avatar answered Oct 21 '25 02:10

B2725