Caching Generated Data

Sometimes it can be worthwhile to cache generated data to be used across requests. There are two main methods of caching data, each suited to a specific need.

  • Doctrine Cache is suitable for highly dynamic data.

    Cache times should be relatively small to ensure that data remains fresh. Examples of this data include database results, entity hydration results, and fully rendered content that is ready to serve.

  • ConfigCache caches static data in files to be included by PHP at runtime.

    These files are generated at time of deployment and should not change during their lifetime. Examples of suitable applications here is cached routing and URL generator data.

Note: See the advanced section for more information on using ConfigCache.

Doctrine Cache

Nice supports Doctrine's Cache component through an extension. This allows for easy storage and retrieval of generated information, using any number of cache backends.

The first step is requiring the Nice Doctrine Cache bridge in your project. You can do this by updating your composer.json or running composer require at the command line.

  • Example composer.json:

        "require": {
            "nice/framework": "~1.0",
            "nice/doctrine-cache": "~1.0"

    Then run composer update at the command line.

  • Using the composer command line tool, after installing Nice:

    composer require nice/doctrine-cache:~1.0

With Doctrine Cache is installed, the next step is registering the CacheExtension with your Nice Application.

use Nice\Extension\CacheExtension;

// ...

$app = new Application();
$app->appendExtension(new CacheExtension(array(
    'connections' => array(
        'default' => array(
            'driver' => 'redis',
            'host' => ''

With the above configuration, Nice will create the following service:

Using the Doctrine Cache is straightforward. Data can be stored using the save method and retrieved using the fetch method.

// ...
$app = new Application();
// ...

// Configure your routes
$app->set('routes', function (RouteCollector $r) {
    $r->map('/hello/{name}', null, function (Application $app, Request $request, $name) {
        $cache = $app->get('cache.default');
        $cache->save('last-hello', $name);

        return new Response('Hello, ' . $name . '!');

    $r->map('/last-hello', null, function (Application $app) {
        $cache = $app->get('cache.default');
        $name = $cache->fetch('last-hello');

        if (!$name) {
            return new Response('I have not said "Hello" to anyone :(');

        return new Response('Last said hello to: ' . $name);

Powered by Codex 1.1.0