PHPackages                             heyday/silverstripe-cacheinclude - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. heyday/silverstripe-cacheinclude

ActiveSilverstripe-vendormodule[Caching](/categories/caching)

heyday/silverstripe-cacheinclude
================================

Fast Caching for SilverStripe

5.2.4(1y ago)4557.2k↓27.8%21[1 issues](https://github.com/WPP-Public/akqa-nz-silverstripe-cacheinclude/issues)[1 PRs](https://github.com/WPP-Public/akqa-nz-silverstripe-cacheinclude/pulls)2PHP

Since Sep 26Pushed 1y ago29 watchersCompare

[ Source](https://github.com/WPP-Public/akqa-nz-silverstripe-cacheinclude)[ Packagist](https://packagist.org/packages/heyday/silverstripe-cacheinclude)[ RSS](/packages/heyday-silverstripe-cacheinclude/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (41)Used By (2)

SilverStripe Cache Include
==========================

[](#silverstripe-cache-include)

[![Build Status](https://camo.githubusercontent.com/dc1ae9cb518c17ec9d6ae5c4bc99ddb4286804f5973af8be2a86bfefd07a5e14/68747470733a2f2f7472617669732d63692e6f72672f6865796461792f73696c7665727374726970652d6361636865696e636c7564652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/heyday/silverstripe-cacheinclude)

Template caching based on urls not DB queries.

Features
--------

[](#features)

- Cache keys are built from information available in request object (means no DB calls)
- Invalidation hooks for when DataObject's are modified
- Uses `doctrine/cache` library, providing many cache backends
- Uses Symfony Expression language for fine-grained invalidation control
- Support for `` syntax in templates
- Support for `` syntax in templates
- A full request cache that includes the ability to substitute security tokens
- Highly customisable
- Sets request header when cache is hit for easier testing e.g hit at Thu, 03 Mar 2022 14:23:41 -0600

Installation
------------

[](#installation)

```
$ composer require heyday/silverstripe-cacheinclude:~5.0
```

How to use
----------

[](#how-to-use)

### Enabling

[](#enabling)

To be able to invalidate caches from DataObject writes, add the `InvalidationExtension`:

1. C te a config file `mysite/_config/caching.yml`
2. Add the following to the yml file

```
---
After: 'silverstripe-cacheinclude/*'
---
SilverStripe\ORM\DataObject:
  extensions:
    - Heyday\CacheInclude\SilverStripe\InvalidationExtension
```

### Template Usage

[](#template-usage)

Cache a section of a template:

```

```

Cache an included template (assumes a cache block config name of `SomeTemplateName`):

```

```

Cache an included template with a different cache block config name:

```

```

### Cache block config

[](#cache-block-config)

For each cache block that is used, you need a corresponding config provided to `CacheInclude`.

The following is an example of a config for `SomeCacheBlock` and `AnotherCacheBlock`:

`mysite/_config/caching.yml`

```
---
After: 'silverstripe-cacheinclude/*'
---
Injector:
  CacheIncludeConfig:
    class: Heyday\CacheInclude\Configs\ArrayConfig
    properties:
      Config:
        SomeCacheBlock:
          context: full
          contains:
            - MyDataObject
        AnotherCacheBlock:
          context: no
          expires: +1 hour
```

### Configuration options

[](#configuration-options)

Key creation options:

#### `context`

[](#context)

Context is a method to tell the key creator what information about the request to include in the created key.

Possible values:

- `no`
    - Key created is independent of the request
- `host`
    - Key created with the host name, useful for when using Subsites or multiple base domains
- `page`
    - Key is created based on url, but not including GET variables
- `full`
    - Key is created based on url, including GET variables

#### `expires`

[](#expires)

Possible values:

- (string)
    - A string to pass into strtotime e.g. '+1 hour'
- (int)
    - A number of seconds

#### `member`

[](#member)

Possible values:

- `true`
    - Will create a new cache per logged in member
- `any`
    - Will create a new cache members as a group (and another key when a person is not logged in)

#### `versions`

[](#versions)

Possible values:

- (int)
    - Set this to an integer to make the specified number of versions of the cache

This is useful for when a cache block contains random content, but you still want caching.

e.g. set to 20 to get 20 (potentially) different version of a cache block.

Cache invalidation options

#### `contains`

[](#contains)

- (array)
    - An array of class names that if a record saved matches the cache will invalidate

#### `invalidation_rules`

[](#invalidation_rules)

- (array)
    - An array of rules written in the available expression language. If a rule is matched the cache will invalidate

The Expression Language is provided by Symfony, but also has the following available:

##### Variables

[](#variables)

- `item`
- `action`

##### Functions

[](#functions)

- `list()`
- `instanceof()`

Theses can be used to do the following:

```
  invalidation_rules:
    - "instanceof(item, 'CreativeProfile') and item.ID in list('CreativeProfile').sort('Created DESC').limit(4).getIDList()"

```

Full request caching
--------------------

[](#full-request-caching)

CacheInclude comes with a `RequestCache` service that can be added to cache full request objects for use in high load sites.

### Enabling

[](#enabling-1)

To enable the full request cache, the `RequestCacheMiddleware` needs to be applied and a `Global` config block needs to be created:

```
---
After: '#cacheinclude'
---
SilverStripe\Core\Injector\Injector:
  CacheIncludeConfig:
    class: Heyday\CacheInclude\Configs\ArrayConfig
    properties:
      Config:
        Global:
          contains:
            - SilverStripe\CMS\Model\SiteTree
          context: full
          expires: '+ 1 hour'
---
After: '#coresecurity'
---
SilverStripe\Core\Injector\Injector:
  SilverStripe\Control\Director:
    properties:
      Middlewares:
        RequestCacheMiddleware: '%$RequestCacheMiddleware'
```

**Note:** the `After:` condition in the above example is important. Without it, the middleware that handles request caching will run before SilverStripe's authentication middleware - meaning that the current user (stored in the session) isn't available. This could result in cache contamination between users, or between guests &amp; registered users.

Full request caching increases performance substantially but it isn't without a cost. It can be hard to configure, as there are numerous cases where you don't want to either cache a request or alternatively serve a cached request.

To help in this there is quite a bit you can do out of the box to configure the way that caching is handled.

The following gives some demonstration of how to configure things and what you can do:

```
Injector:
  RequestCacheMiddleware:
    class: 'Heyday\CacheInclude\SilverStripe\RequestCacheMiddleware'
    constructor:
      0: '%$CacheInclude'
      1: '%$CacheIncludeExpressionLanguage'
      2: 'Global'
    properties:
      Tokens:
        - '%$SilverStripe\Security\SecurityToken'
      SaveExcludeRules:
        - 'request.getUrl() matches "{^admin|dev}"'
      SaveIncludeRules:
        - "request.httpMethod() == 'GET'"
        - 'response.getStatusCode() == 200'
      FetchExcludeRules:
        - 'request.getUrl() matches "{^admin|dev}"'
      FetchIncludeRules:
        - "request.httpMethod() == 'GET'"
```

As you can see above there are some variables made accessible to you in the expression language.

The following is made available in the "Save" rules:

- `request`
- `response`
- `member`
- `session`

The following is made available in the "Fetch" rules:

- `request`
- `member`
- `session`

Additional variables can be provided through the injector system.

```
Injector:
  RequestCacheMiddleware:
    properties:
      ExtraExpressionVars:
        'hello': 'Something'
```

Customisation
-------------

[](#customisation)

Because of the heavy usage of dependency injection and the SilverStripe `Injector` component, most parts of `CacheInclude` can be completely customised by replacing the standard classes with ones of your own.

### Key Creators

[](#key-creators)

`CacheInclude` comes built in with one key creator `Heyday\CacheInclude\KeyCreators\ControllerBased`. This key creator makes keys based on the config supplied in yaml, the current request and the environment.

You can create your own key creators by extending the `KeyCreatorInterface` and specifying the creator's service name from the template.

```

Some content

```

```
class MyKeyCreator implements \Heyday\CacheInclude\KeyCreators\KeyCreatorInterface
{
    public function getKey($name, $config)
    {
        return [
           'key',
           'parts'
        ];
    }
}
```

License
-------

[](#license)

SilverStripe CacheInclude is released under the [MIT license](http://heyday.mit-license.org/)

Contributing
------------

[](#contributing)

### Unit Testing

[](#unit-testing)

```
$ composer install --prefer-dist --dev
$ phpunit
```

### Code guidelines

[](#code-guidelines)

This project follows the standards defined in:

- [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md)
- [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md)
- [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)

Run the following before contributing:

```
$ php-cs-fixer fix .
```

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance41

Moderate activity, may be stable

Popularity42

Moderate usage in the ecosystem

Community32

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor1

Top contributor holds 57.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~115 days

Recently: every ~121 days

Total

40

Last Release

479d ago

Major Versions

2.0.4 → 3.0.02013-07-28

3.1.0 → 4.0.02014-04-09

2.0.x-dev → 4.0.12014-07-25

4.0.x-dev → 5.0.02019-01-09

4.2.3 → 5.1.32023-02-22

### Community

Maintainers

![](https://www.gravatar.com/avatar/de4d8d61f202a03e88c3ed30cce3bfedbc6f56a16e3f3b25546c61aadc51bca2?d=identicon)[heyday](/maintainers/heyday)

---

Top Contributors

[![camspiers](https://avatars.githubusercontent.com/u/51294?v=4)](https://github.com/camspiers "camspiers (80 commits)")[![wilr](https://avatars.githubusercontent.com/u/101629?v=4)](https://github.com/wilr "wilr (14 commits)")[![priyashantha](https://avatars.githubusercontent.com/u/6611682?v=4)](https://github.com/priyashantha "priyashantha (11 commits)")[![stecman](https://avatars.githubusercontent.com/u/2230769?v=4)](https://github.com/stecman "stecman (9 commits)")[![Mohanatheesan26](https://avatars.githubusercontent.com/u/48876593?v=4)](https://github.com/Mohanatheesan26 "Mohanatheesan26 (7 commits)")[![christopherdarling](https://avatars.githubusercontent.com/u/178039?v=4)](https://github.com/christopherdarling "christopherdarling (4 commits)")[![lozcalver](https://avatars.githubusercontent.com/u/1655548?v=4)](https://github.com/lozcalver "lozcalver (3 commits)")[![stevie-mayhew](https://avatars.githubusercontent.com/u/1953220?v=4)](https://github.com/stevie-mayhew "stevie-mayhew (3 commits)")[![RVXD](https://avatars.githubusercontent.com/u/1586761?v=4)](https://github.com/RVXD "RVXD (2 commits)")[![bendubuisson](https://avatars.githubusercontent.com/u/3079189?v=4)](https://github.com/bendubuisson "bendubuisson (2 commits)")[![ClemTar](https://avatars.githubusercontent.com/u/12903433?v=4)](https://github.com/ClemTar "ClemTar (1 commits)")[![tractorcow](https://avatars.githubusercontent.com/u/936064?v=4)](https://github.com/tractorcow "tractorcow (1 commits)")[![tyrannosaurusjames](https://avatars.githubusercontent.com/u/3037783?v=4)](https://github.com/tyrannosaurusjames "tyrannosaurusjames (1 commits)")[![timhiggs](https://avatars.githubusercontent.com/u/3209433?v=4)](https://github.com/timhiggs "timhiggs (1 commits)")[![jcop007](https://avatars.githubusercontent.com/u/13442789?v=4)](https://github.com/jcop007 "jcop007 (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/heyday-silverstripe-cacheinclude/health.svg)

```
[![Health](https://phpackages.com/badges/heyday-silverstripe-cacheinclude/health.svg)](https://phpackages.com/packages/heyday-silverstripe-cacheinclude)
```

###  Alternatives

[eliashaeussler/typo3-warming

Warming - Warms up Frontend caches based on an XML sitemap. Cache warmup can be triggered via TYPO3 backend or using a console command. Supports multiple languages and custom crawler implementations.

20229.9k](/packages/eliashaeussler-typo3-warming)[silverstripe/staticpublishqueue

Static publishing queue to create static versions of pages for enhanced performance and security

45135.4k4](/packages/silverstripe-staticpublishqueue)[tbbc/cache-bundle

Symfony Bundle - Cache abstraction and method annotations for controlling cache

3613.1k](/packages/tbbc-cache-bundle)[pstaender/silverstripe-redis-cache

Enables Redis cache for SilverStripe

1199.1k](/packages/pstaender-silverstripe-redis-cache)[silverstripe-terraformers/keys-for-cache

Silverstripe cache key management

1726.6k](/packages/silverstripe-terraformers-keys-for-cache)[steadlane/silverstripe-cloudflare

This module aims to relieve the stress of using Cloudflare caching with any SilverStripe project. Adds extension hooks that clears Cloudflare's cache for a specific page when that page is published or unpublished.

243.7k](/packages/steadlane-silverstripe-cloudflare)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
