Php Yii:传递到动作的参数与动作中的负载模型


Php Yii: parameter passing to action vs load model in action

我正在尝试优化我的代码,但我无法决定使用什么,以及哪种是最佳实践。

我有一个视图,比如view1.php,它是由一个操作渲染的。现在view1包含一个模型$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
}

我应该将整个对象传递给动作,还是最好只在动作中重新加载一次模型?谢谢,我希望我解释得很好

我更喜欢加载数据库中的那一行。这是一个优化,我不会担心,直到它成为一个问题。

您可以将模型存储在控制器中,以防止多次运行同一查询:

// 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;
}

这是我在这里学到的一个技巧。