I just started using CodeIgniter, and have really been happy with the results.
The one thing I've noticed is that I seem to be selecting different parts of a row with different parts of a model.
An example would be where on a page I need to get the current user's username, then farther down I need their email address. These are separate functions in the model (and therefore, separate queries). It annoys me knowing I could merge them into one query (saving overhead), but if I did that then I would loose the modularization the MVC model gives me (on plenty of other pages I just need the username or email, not both). Any suggestions on how to g开发者_如何学Pythonet past this?Yes, but I have a specific function returning part of a row, and another function, returning another section of a row. I need this because most pages only need one section of the row, but some pages need both, this causes my code to run two queries. This is just one example. There are many. I was curious if there is a design pattern for this.
Youre essentially talking about lazy loading. So in your model you use something to track the state of the persisted properties, i.e. whether they have been loaded, modified, or if the model is completely new and not yet in the db. Then your getters for each property first check state, and if something is not yet loaded and the model isnt "new" then they query for that property and set it on the model before returning the value.
So your magic get might look like (pseudo code - youll have to translate to CI):
public function __get($property){
if($this->isPersisted($property) && !$property->isLoaded() && !$this->isNew()){
$this->$property = $this->db
->select($this->getColumn($property))
->from($this->tableName)
->where('id = ?', $this->id)
->fetchColumn(0);
}
return $this->property;
}
精彩评论