开发者

Lots of getters and setters in a Model

开发者 https://www.devze.com 2023-02-14 22:33 出处:网络
I\'m using CodeIgniter for an application that I\'m writing and I\'ve got a question regarding models.

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 开发者_如何学JAVAdatabase 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

$items = $query->result();
foreach ($items as $item) {
  $x = $item->field1;
  $y = $item->field2;
}

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.


I haven't used CodeIgniter yet, but this is probably a more general question. I believe there's no wrong or right.

If your data needs some sort of validation or cleanup before going into the database, using setters would be a good solution. Also, if your raw data needs a conversion before being used throughout the application, then you will probably use getters to avoid unnecessary duplicate code.

Otherwise I think it's absolutely okay to pull rows, even in the CodeIgniter User Guide they do that.

0

精彩评论

暂无评论...
验证码 换一张
取 消