Question

I have some controllers, where __constructor is similar in every of it. How to avoid copy-paste of similar code and write it in a one place?

Was it helpful?

Solution

You can create a controller lets say ParentController and extends it with base controller then add __contructor in that. Now in all of your controllers where you want this constructor just extend your controllers with the created controller ParentController.

ParentController.php:

class ParentController extends CI_Controller {

    function __construct() 
    {
        parent::__construct();
        //your constructor code here..
    }
}

Now the controllers in which you want the same constructor can be extended from ParentController : ClassA.php

class ClassA extends ParentController {
    function __construct() 
    {
        parent::__construct();
    }
    //your first controller
}

ClassB.php

class ClassB extends ParentController{
    function __construct() 
    {
        parent::__construct();
    }
    //Your second controller
}

Hope this helps.

OTHER TIPS

Best place for ParentController.php would be application/core/ folder.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top