Search code examples
phpcodeignitermodel-view-controllerdesign-patternsmodel

General rule - when to use a model (Codeigniter)


I was just curious as to what the rule of thumb was for models. Generally, I use them only for situations where I need to add/edit or update database entries for an object.

However, I'm building an app at the moment that has a "config" table which holds various data, such as last updated, which will control when certain features in the app should be displayed. In this instance, I will mostly need to retrieve data from the config table. Is it worth putting these config methods in model?

I'm interested to hear how more experienced coders approach the MVC methodology in CI.

Example pseudo methods (e.g., what methods relating to the same object you'd use in the model and the controller) would be most helpful.


Solution

  • "Is it worth putting these config methods in model?"

    yes, absolutely, if only to prevent you from writing the same getters and setters in every controller that has deal with your table of configuration settings. Write your getters and setters once (ideally in a generalized way in MY_Model) and write your complex queries once in the model, then call them in as many libraries, controllers, or views as desired.

    By employing models you are able to code to an interface and not an implementation.

    Meaning there is a benefit of abstracting your model from your controller in that your controllers can be agnostic as to what ways your data is stored. You can decided to switch your data from database to xml to ini files as long as the models methods consistently offer up results in the format the controller expects. In short, when you switch your data source, you'd need only update your model's internal methods and not your controllers.

    Lastly, it is permissible by the rules of MVC, I believe, to allow views to request data directly from models. To this end you may build CodeIgniter helpers for use in views that use the model to retrieve configuration settings, in much the same way that the native config_item() common function works.