Skip to main content

Caching

To improve performance, views can be cached. Before this chapter, we recommend going through the chapter about [Thomas, I need a link here]Response and HTTP caching[/Thomas, I need a link here].

Introduction​

Via ControllerAdapter::assignViewCacheControl() you can instruct n2n to cache views that are output with ControllerAdapter::forward(). With ControllerAdapter::forwardCache() you can read a view from the cache and output it. If possible, you should do this before time-consuming database queries.

class ExampleController extends ControllerAdapter {

public function index(ExampleDao $exampleDao) {
$this->assignViewCacheControl(new \DateInterval('PT30M'));

// if valid cache is available it will be send to response
if ($this->forwardCache('view\bar.html')) {
return;
}

// renew cache
$items = $exampleDao->getItems();
$this->forward('view\bar.html', array('items' => $items));
}
}

forwardCache() returns true if a valid cached version of the view exists. In this case the method call can be ended right away. Otherwise the view is reassembled and cached (in this example for 30 minutes).

Characteristics​

In most cases it makes sense to cache different versions of a view. For example, you want to use the same view for every article, but every article has a different content. So that n2n can distinguish these versions from each other, you have to define characteristics for each version. You do this via the second parameter of ControllerAdapter::assignViewCacheControl(). A different version of the view is cached for each different characteristic.

public function doArticle($id, ArticleDao $articleDao) {
$this->assignViewCacheControl(new \DateInterval('PT30M'), array('id' => $id));

if ($this->forwardCache('view\article.html')) {
return;
}

$article = $articleDao->getArticleById($id);
if (null === $article) {
throw new PageNotFoundException();
}

$this->forward('view\article.html', array('article' => $article));
}

Since in this example an article can be clearly identified by its ID, the ID is suitable as a characteristic. One version of the view is now cached per ID.

Import Cache​

Views that you include in other views via $view->import() can also be cached. For this you need the type n2n\ui\view\ViewCacheControl:

<?php $view->import('view\baz.html', array('param' => $param),
new ViewCacheControl(new \DateInterval('PT30M'), array('charac' => $charac))) ?>

$view->import() now loads the view baz.html from the cache if a valid version is available.

Managing the Cache​

How to get the view's CacheStore and its php-doc. --> To be reviewed with Thomas.