CodeIgniter Forums
Where to place functions that work with database - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Where to place functions that work with database (/showthread.php?tid=73546)



Where to place functions that work with database - pcasalegno - 05-07-2019

Hi guys,

I'm sure this is a very remedial question, but I'm not quite sure what is best-practice here.

I have one model for each table in my database, and I have a controller that does a lot of calculations involving data from many tables.  I'd like to create a bunch of functions to make my code cleaner (and hopefully take some of the code out of the controller).

I thought to use helper functions, but I wasn't sure how to access database objects in the helper functions; since my "use" statements are in the controller.

Thanks,
Phil


RE: Where to place functions that work with database - donpwinston - 05-07-2019

Create a class or two that encapsulates your business rules. Put them in the Library folder. Then you can use them in your controller and keep your controllers slim.


RE: Where to place functions that work with database - php_rocs - 05-07-2019

@pcasalegno,

....or you could make your models do a lot of the lifting (you could use database views and private methods/functions in models that do a lot of the calculations) and return your data in a format where all you have to do is display it.


RE: Where to place functions that work with database - pcasalegno - 05-07-2019

(05-07-2019, 05:05 PM)donpwinston Wrote: Create a class or two that encapsulates your business rules. Put them in the Library folder. Then you can use them in your controller and keep your controllers slim.

This was exactly what I was looking for.  Thanks!


RE: Where to place functions that work with database - pcasalegno - 05-07-2019

(05-07-2019, 07:01 PM)php_rocs Wrote: @pcasalegno,

....or you could make your models do a lot of the lifting (you could use database views and private methods/functions in models that do a lot of the calculations) and return your data in a format where all you have to do is display it.

This is a great idea, and probably more in-keeping with the MVC concept.  Thanks!


RE: Where to place functions that work with database - MGatner - 05-14-2019

I like both ideas, and probably both are applicable depending on your code. I typically put things into my Model if it is primarily dealing with that models table and (moderately) its relations, and reserve make a separate class (Library) for something that is going to "run" my existing models (similar to Controllers but not as a integral part of the MVC user interaction).