CakePHP v3: Cache in View

Hi All

I have 3-4 different circumstances where I have identified that caching some of the html that is built when rendering a view would be advantageous. One view in particular uses up to 6 joined tables and would be ideal to use a cached version of the html.

I’m assuming I’m right in thinking that I can put the cache code in my View (as opposed to the controller)?

I’ve looked at some of the code examples in
http://book.cakephp.org/3.0/en/core-libraries/caching.html

But can’t seem to get it working. I have the following in my app.php

	'general' => [
		'className' => 'File',
		'duration' => '+1 week',
        'path' => CACHE . 'html/',
		'prefix' => 'cake_html_'
	],

The following is a code snippet from the view.ctp

//read from cache::general
$cacheContents = Cache::read('mfc-' . (string)$manufacturer->id, 'general');

if ($cacheContents !== false) {

    echo $cacheContents;

} else {

    // Generate cache data
    $this->loadHelper('GarmentDisplay');
    $strBuiltHTML = $this->GarmentDisplay->displayGarmentsinHTML($garments);
    echo $strBuiltHTML;

    // Store data in cache
    Cache::write('mfc-' . (string)$manufacturer->id, $strBuiltHTML, 'general');

}

Error is
Class ‘Cache’ not found

⟩ include
CORE\src\View\View.php, line 992
⟩ Cake\View\View->_evaluate
CORE\src\View\View.php, line 952
⟩ Cake\View\View->_render
CORE\src\View\View.php, line 587
⟩ Cake\View\View->render
CORE\src\Controller\Controller.php, line 611
⟩ Cake\Controller\Controller->render
CORE\src\Routing\Dispatcher.php, line 120
⟩ Cake\Routing\Dispatcher->_invoke
CORE\src\Routing\Dispatcher.php, line 87
⟩ Cake\Routing\Dispatcher->dispatch
ROOT\webroot\index.php, line 36

View elements already have caching support so why not just use that instead? You just have to specify the cache key in View::element() options. Check manual for more info.

Brilliant thank you so much ADmad

I had missed that in the docs for some reason!

For convenience; here are the two pages that I found useful;

http://api.cakephp.org/3.2/class-Cake.View.View.html#_cache

http://book.cakephp.org/3.0/en/views.html#Cake\View\View::cache