silverstripe-framework/docs/en/02_Developer_Guides/01_Templates/07_Caching.md

47 lines
1.0 KiB
Markdown
Raw Normal View History

2014-10-13 09:49:30 +02:00
title: Caching
2015-08-05 11:34:35 +02:00
summary: Reduce rendering time with cached templates and understand the limitations of the ViewableData object caching.
2014-10-13 09:49:30 +02:00
# Caching
## Object caching
All functions that provide data to templates must have no side effects, as the value is cached after first access. For
example, this controller method will not behave as you might imagine.
```php
2014-10-13 09:49:30 +02:00
private $counter = 0;
2017-08-03 06:25:49 +02:00
public function Counter()
{
2014-10-13 09:49:30 +02:00
$this->counter += 1;
return $this->counter;
}
```
2014-10-13 09:49:30 +02:00
```ss
2014-10-13 09:49:30 +02:00
$Counter, $Counter, $Counter
// returns 1, 1, 1
```
2014-10-13 09:49:30 +02:00
When we render `$Counter` to the template we would expect the value to increase and output `1, 2, 3`. However, as
`$Counter` is cached at the first access, the value of `1` is saved.
## Partial caching
Partial caching is a feature that allows the caching of just a portion of a page. Instead of fetching the required data
2017-02-23 20:39:57 +01:00
from the database to display, the contents of the area are fetched from a [cache backend](../performance/caching).
2014-10-13 09:49:30 +02:00
```ss
2014-10-13 09:49:30 +02:00
<% cached 'MyCachedContent', LastEdited %>
$Title
<% end_cached %>
```