3

I'm developing an application, where the same function I'm writing for some controllers. So I wanted one common function for all controllers. Please help me out I've stucked up with this. The work would be more appreciated.

5
  • 2
    Are you trying to share one common function among all controllers? I'm having trouble figuring out what you're asking Commented Dec 5, 2013 at 6:07
  • If you are indeed attempting to share a function between controllers, it should be part of a helper (or maybe library or model, depending on what that function does). In fact, depending on what the function does, you might even want to put it in a base controller class. We need more details. Commented Dec 5, 2013 at 6:13
  • I think a helper function would be nice. Commented Dec 5, 2013 at 6:15
  • If you go for a helper function you can't access your models though. For this I would suggest you to go for the My Contoller trick. Commented Dec 5, 2013 at 6:18
  • You can extend base class with other classes Commented Dec 6, 2013 at 12:33

3 Answers 3

3

You can develop a helper or library.

codeigniter version 2 : https://codeigniter.com/userguide2/general/creating_libraries.html

codeigniter version 3 : https://codeigniter.com/user_guide/general/creating_libraries.html?highlight=library

Sign up to request clarification or add additional context in comments.

Comments

2

You can create MY_Controller class in application/core

Class MY_Controller Extends CI_Controller{

    public function __construct(){
        parent::__construct();
    }

    public function common(){
        // code here
    }
}

Now extend every class with MY_Controller and the function will be available for each class

Class Test Extends MY_Controller{

    public function __construct(){
        parent::__construct();
    }
}

When in the url you call

http://localhost/app/test/common

This will work.

Comments

0

create a model class and create that all function after that extend that model all model classes .you can use one function different controller.other wise you can use Cms helper.this is the best way call a common function in different controller.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.