Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a big Controller into different files in Codeigniter?

Tags:

codeigniter

The Codeigniter Controller I am writing is getting big. How do I split the code into different files?

like image 532
Andy J. Avatar asked Mar 21 '26 13:03

Andy J.


1 Answers

Things you definitely should be doing:

  • Anything that is strictly related to the controller, leave it alone.

  • Make sure you move at least 99% of the view logic (html) into proper view files.

  • Move all data processing into a Model. This includes database interaction, file manipulation, and form processing.

Things you probably should be doing:

  • Anything that you are repeating frequently, create a function for it instead if possible.

  • Gather all related functions and create Libraries in application/libraries/.

  • Whatever is left over, like independent common functions, create a helper file in application/helpers. If you know you will always need them, perhaps call it global_helper.php or something similar. You can break these out into different files later if this gets too crowded.

  • Use a base controller. Create the file core/MY_Controller.php. Use this for anything you know you will need available globally to your controllers. You can create as many extensions you like in this file for different controller "types" (like Front_Controller, Back_Controller, Login_Controller), just make sure to extend the class in your controller files like Blog_Controller extends MY_Controller.

Make sure you have read the user guide thoroughly so you can take advantage of what the framework has built-in, you may be writing unnecessary code because you are unaware of the available features.

like image 119
Wesley Murch Avatar answered Mar 23 '26 19:03

Wesley Murch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!