I’m using CodeIgniter for an application that I’m writing and I’ve got a question regarding models.
What I’m trying to figure out is if I should have a getter and setter method for each field in the database or should I just pull in the entire row and just grab the particular column I need inside of PHP. I feel that having a whole bunch of gets and sets could lead to someone producing a lot of unnecessary calls to the database. So am I thinking about this wrong or right? Should each DB field have its own get/set or is that a waste?
As usual, “it depends”. It depends where you’re going to use the results.
Normally your queries should only hit the database for the fields each request needs. eg “select field1, field2 from mytable” rather than “select * from mytable”. Then use CodeIgniters functionality to get the field values out – eg
If, however, you are passing a whole “item” object around to other functions then you’ll probably need the query to retrieve all the columns that the object is made up of otherwise some functions may receive invalid data.
You could also try and implement some form of “lazy loading” whereby you pass some/most of the data in the original object then when a method requests other field data the getter method makes another request to the database for the new info. But this can get much more complicated.
So
– for simple results within the model or methods that return something specific other than a particular object – use as small a query as possible.
– for methods that return a particular object of your model then use as small a query as possible that will return the full info for that object.
In either case – make the query return what is needed.