我正在尝试优化我的代码,我无法决定使用什么,以及最佳做法。
我有一个视图说 view1.php ,由动作呈现。现在 view1 包含通过其操作传递给视图的模型 $ model ;现在我再次使用 $ model 在另一个不同的操作中使用它,如下所示:
view1.php:
$studyDetails = $this->actionStudyDetails($model);
在StudyDetails动作中,我将使用$ model,
StudyController.php:
public function actionStudyDetails($model){
//do some processing of the model here and return an object
}
我的问题是,假设模型非常大,传递已经加载的整个对象是个好主意吗?在优化方面,还是最佳实践?
或者我应该只传递id或主键说$ model-> id?然后加载模型;让我的行动像这样:
StudyController.php:
public function actionStudyDetails($id){
$model = $this->loadModel($id);
//do some processing of the model here and return an object
}
我应该将整个对象传递给动作还是最好只在动作内部重新加载模型?谢谢,我希望我解释得很好
答案 0 :(得分:2)
我更喜欢在数据库中加载该单行。这是一个我不会担心的优化,直到它成为一个问题。
您可以将模型存储在控制器中,以防止多次运行相同的查询:
// Store model to not repeat query.
private $model;
protected function loadModel( $id = null )
{
if($this->model===null)
{
if($id!==null)
$this->model=SomeModel::model()->findByPk($id);
}
return $this->model;
}
这是我学会here的一招。