sirjay
sirjay

Reputation: 1766

Yii2: how to reduce behaviors() db queries when loading controller?

I am getting model object 3 times (Yii2) to load view controller. This makes my page to load slow. How to reduce it?

public function behaviors()
{
    return [
        'httpCache' => [
            'class' => 'yii\filters\HttpCache',
            'only' => ['view'],
            'lastModified' => function ($action, $params) {
                $post = $this->findModel(Yii::$app->request->get('id'));
                return strtotime($post->updated);
            },
            'etagSeed' => function ($action, $params) {
                $post = $this->findModel(Yii::$app->request->get('id'));
                return serialize([$post->updated, $post->views, $post->comments, Yii::$app->user->isGuest ? 0 : 1]);
            }
        ],
    ];
}

public function actionView($id)
{
    $model = $this->findModel($id);

    return $this->render('view', [
        'model' => $model,
    ]);
}

Upvotes: 3

Views: 163

Answers (1)

rob006
rob006

Reputation: 22174

You can cache model instance at controller level:

private $_models = [];

protected function findModel($id) {
    if (!array_key_exists($id, $this->_models)) {
        $this->_models[$id] = MyModel::findOne($id);
        if ($this->_models[$id] === null) {
            $this->notFound();
        }
    }

    return $this->_models[$id];
}

Only first call of findModel() will query DB, next calls will return already instantiated object.

Upvotes: 1

Related Questions