CodeIgniter Forums
Is adding functions to CI_Controller bad practice? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Is adding functions to CI_Controller bad practice? (/showthread.php?tid=50512)



Is adding functions to CI_Controller bad practice? - El Forum - 03-28-2012

[eluser]coldscooter[/eluser]
I have a function that I wish to be available to all controllers.

Should I simply add this function to the CI_Controller class?


Is adding functions to CI_Controller bad practice? - El Forum - 03-28-2012

[eluser]skunkbad[/eluser]
[quote author="coldscooter" date="1332968903"]I have a function that I wish to be available to all controllers.

Should I simply add this function to the CI_Controller class?[/quote]

No, you should extend the CI_Controller class with a MY_Controller class. Then all of your controllers will extend MY_Controller instead of CI_Controller.


Is adding functions to CI_Controller bad practice? - El Forum - 03-28-2012

[eluser]InsiteFX[/eluser]
If a function is used in more then one Controller then you should create a MY_Controller and add the function there.

See:
Phil Sturgeon - CodeIgniter Base Classes: Keeping it DRY



Is adding functions to CI_Controller bad practice? - El Forum - 03-28-2012

[eluser]coldscooter[/eluser]
Thanks for the response. Please could you explain the reason why it is bad practice. Assuming that I know that I will always want this function available to all controllers.


Is adding functions to CI_Controller bad practice? - El Forum - 03-28-2012

[eluser]coldscooter[/eluser]
If i create a My_Controller, then wouldn't i need to change all my other controllers to extend that? Or does it somehow extend the My_Controller without explicitly stating it in all the other controllers?


Is adding functions to CI_Controller bad practice? - El Forum - 03-28-2012

[eluser]Matalina[/eluser]
The basic answer, don't change the core. Updates of the core will be more difficult.


Is adding functions to CI_Controller bad practice? - El Forum - 03-28-2012

[eluser]coldscooter[/eluser]
Thanks, that does make sense to me.


Is adding functions to CI_Controller bad practice? - El Forum - 03-28-2012

[eluser]TWP Marketing[/eluser]
[quote author="coldscooter" date="1332969629"]If i create a My_Controller, then wouldn't i need to change all my other controllers to extend that? ...[/quote]

Yes, All of YOUR controllers will extend MY_Controller, which itself extends the core CI controller. Read the link by Phil Sturgeon about why this is desirable. This way, if the core code is updated, you should ,b>not</b> need to dig into the new code to re-apply your methods/functions.