在几乎每个模型中,我最终都会编写类似于以下示例代码的代码。它会检查是否发送了诸如limit
, order
, conditions
... 等选项,并据此更改查询。
似乎必须有更好的方法,因为大多数这些东西在许多模型中一遍又一遍地重复。也许我可以使用一种行为?或者也许我完全忽略了其他东西?
就模型代码而言,我觉得我试图重新发明轮子,但我真的很想知道轮子是什么——即大多数人如何管理他们的模型代码?我认为模型像这样是“正常的”?寻找这个整体“相似模型代码”概念的最佳实践。
//Restaurant model
function getRestaurants($opts = null) {
//initialize
$findType = 'all';
$params['conditions'] = array();
//order
$params['order'] = 'Restaurant.name ASC';
if(!empty($opts['order'])) $params['order'] = $opts['order'];
//limit
if(!empty($opts['limit'])) {
$params['limit'] = $opts['limit'];
if($params['limit'] == 1) $findType = 'first';
}
/*... ETC ETC
- can pass conditions, pricing, days open....etc
- obviously some things are only for this model, but things like
limit, order, conditions...etc are for all my models
*/
//pagination
$paginate = false;
if(isset($opts['paginate'])) {
if($opts['paginate']) {
$paginate = true;
}
}
//either return the paginate options just created
if($paginate) {
return $params;
//or return the restaurant data found
} else {
$data = $this->find($findType, $params);
return $data;
}
}
在某些情况下,还有更复杂的事情,例如 - 是否根据发送的选项包含/加入某些模型……等等。
我正在尝试坚持 MVC 概念并将我所有的数据库内容保留在模型中。