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.
Extending a controller in another controller is not really good. Building with MVC and especially with CI, you have other options to achieve this.
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.
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With