yii\base\View::beginCache PHP Method

beginCache() public method

This method will display cached content if it is available. If not, it will start caching and would expect an View::endCache call to end the cache and save the content into cache. A typical usage of fragment caching is as follows, php if ($this->beginCache($id)) { ...generate content here $this->endCache(); }
public beginCache ( string $id, array $properties = [] ) : boolean
$id string a unique ID identifying the fragment to be cached.
$properties array initial property values for [[FragmentCache]]
return boolean whether you should generate the content for caching. False if the cached version is available.
    public function beginCache($id, $properties = [])
    {
        $properties['id'] = $id;
        $properties['view'] = $this;
        /* @var $cache FragmentCache */
        $cache = FragmentCache::begin($properties);
        if ($cache->getCachedContent() !== false) {
            $this->endCache();
            return false;
        } else {
            return true;
        }
    }

Usage Example

Example #1
0
 public function testCacheDisabled2()
 {
     $expectedLevel = ob_get_level();
     ob_start();
     ob_implicit_flush(false);
     $view = new View();
     $this->assertTrue($view->beginCache('test'));
     echo "cached fragment";
     $view->endCache();
     ob_start();
     ob_implicit_flush(false);
     $this->assertTrue($view->beginCache('test', ['enabled' => false]));
     echo "cached fragment other";
     $view->endCache();
     $this->assertEquals("cached fragment other", ob_get_clean());
     ob_end_clean();
     $this->assertEquals($expectedLevel, ob_get_level(), 'Output buffer not closed correctly.');
 }