Welcome Guest, Not a member yet? Register   Sign In
Handling duplicate private methods in controllers...
#1

[eluser]CISCK[/eluser]
Quick question (which has probably been answered before):

I have multiple controllers that use the same private methods. It's definitely not DRY to write these methods into each controller, so I'm wondering what the best practice is for handling this in CodeIgniter. Do I move the duplicate methods into a helper? A library? Is this just a matter of personal preference? What would you do?

Thanks in advance.
#2

[eluser]cindor[/eluser]
yep put that method to a helper :=)
#3

[eluser]davidbehler[/eluser]
You can extend the controller and put your methods in the extended controller that you then use in your controllers.

e.g.
libraries/MY_Controller.php
Code:
class MY_Controller extends Controller
{
   function MY_Controller()
   {
     parent::Controller;
   }

   function common_function()
   {
     return "bla";
   }
}

controllers/controller1.php
Code:
class Controller1 extends MY_Controller
{
   function Controller1()
   {
     parent::MY_Controller;
     echo $this->common_function();
   }
}

not tested but should work..more or less Tongue
#4

[eluser]CISCK[/eluser]
Cindor and waldmeister, thanks for the fast replies! I just implemented waldmeister's approach, and it worked perfectly. Thanks again.
#5

[eluser]xwero[/eluser]
IMO extending the controller should be the last solution you think of. If you decide the method should be public you better go for a helper.
You said the method is private and if you want it to stay private than you have no other choice than to put it in an extended controller class and use that class as the parent of the controllers that need it.

The controller is a special case in CI to extend. The MY_Controller file is loaded from the moment the file is found by CI and as you can see in Waldmeister's code you have to extend the actual controller with the full extended controllers name. So to make the best of it you better use a descriptive name to identify the controllers group. This way you can add other classes in that same file if you need to.
Code:
class Group1_controller extends Controller
{
   function __construct()
   {
     parent::Controller;
   }

   private function common_function()
   {
     return "bla";
   }
}
#6

[eluser]CISCK[/eluser]
I'll keep that in mind, xwero. Thanks for the tip!




Theme © iAndrew 2016 - Forum software by © MyBB