yii\filters\PageCache::beforeAction PHP Метод

beforeAction() публичный Метод

This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action.
public beforeAction ( Action $action ) : boolean
$action yii\base\Action the action to be executed.
Результат boolean whether the action should continue to be executed.
    public function beforeAction($action)
    {
        if (!$this->enabled) {
            return true;
        }
        $this->cache = Instance::ensure($this->cache, Cache::className());
        if (is_array($this->dependency)) {
            $this->dependency = Yii::createObject($this->dependency);
        }
        $properties = [];
        foreach (['cache', 'duration', 'dependency', 'variations'] as $name) {
            $properties[$name] = $this->{$name};
        }
        $id = $this->varyByRoute ? $action->getUniqueId() : __CLASS__;
        $response = Yii::$app->getResponse();
        ob_start();
        ob_implicit_flush(false);
        if ($this->view->beginCache($id, $properties)) {
            $response->on(Response::EVENT_AFTER_SEND, [$this, 'cacheResponse']);
            Yii::trace('Valid page content is not found in the cache.', __METHOD__);
            return true;
        } else {
            $data = $this->cache->get($this->calculateCacheKey());
            if (is_array($data)) {
                $this->restoreResponse($response, $data);
            }
            $response->content = ob_get_clean();
            Yii::trace('Valid page content is found in the cache.', __METHOD__);
            return false;
        }
    }

Usage Example

Пример #1
0
 /**
  * @inheritdoc
  */
 public function beforeAction($action)
 {
     if (!$this->enabled) {
         return true;
     }
     if (is_array($this->dependency)) {
         $this->dependency = Yii::createObject($this->dependency);
     }
     if ($this->dependency) {
         $oldDependency = $this->dependency;
         $tag = [$this->varyByRoute ? $action->getUniqueId() : __CLASS__];
         if (is_array($this->variations)) {
             foreach ($this->variations as $factor) {
                 $tag[] = $factor;
             }
         }
         $this->mutexDependency['tag'] = $tag;
         $this->dependency = ['class' => '\\yii\\caching\\ChainedDependency', 'dependOnAll' => false, 'dependencies' => [$oldDependency, Yii::createObject($this->mutexDependency)]];
     }
     return parent::beforeAction($action);
 }