S
S
search742015-02-10 08:23:16
Yii
search74, 2015-02-10 08:23:16

Lazy loading data from database?

I'm trying to do the so-called "lazy" loading of data to reduce the number of requests to one.

protected $_allTimes;
    /**
     * Получить все временные отрезки
     * @return Time[]
     * @throws NotFoundHttpException
     */
    public function getAllTimes() {
        if(!isset($this->_allTimes)){
            echo " я запрос time выполняюсь 1 раз! ";
            $this->_allTimes = Time::find()
                    ->where($this->enabledScope)
                    ->orderBy('from')
                    ->all();
            if($this->_allTimes===null){
                throw new NotFoundHttpException('Ошибка. Не задан ни один временной промежуток!');
            }
        }
        return $this->_allTimes;
    }

    public function getEnabledScope(){
        return ['removed'=>0, 'enabled'=>1]
    }

So, in yii1 1 request is executed, and in yii2 there are many. What is it connected with?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rommcr, 2015-02-10
@rommcr

How is the getAllTimes method called? IMHO there are problems with the call context. In theory, it should be a singleton. Do you happen to create a new object each time?

I
Ivan, 2015-02-10
@IvanCher

In case your code is not of such a plan:

foreach($models as $model) {
  $model-> getAllTimes();
}

If it is similar, then indeed it will make a request for each instance of the model, and with a static variable $_allTimes - only 1 request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question