Tag Archives: cache

Caching Data in Symfony2

It is not too easy to enhance the performance of your application. In Symfony2 you could get benefit from caching. The most effective way to improve performance of an application is to cache the full output of a page and then bypass the application entirely on each subsequent request. The cache is the “middle-man” of the request-response communication between the client and your application. Caching data in Symfony2 with doctrine cache bundle can be implemented as described below.

Installing this bundle can be done through these simple steps:

1. Add this bundle to your project as a composer dependency:

// composer.json
    // ...
    require: {
        // ...
        "doctrine/doctrine-cache-bundle": "~1.0"

2. Add this bundle in your application kernel:

// application/ApplicationKernel.php
public function registerBundles()
    // ...
    $bundles[] = new \Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle();

    return $bundles;


Simply use doctrine_cache.providers.{provider_name} to inject it into the desired service.

Check the following sample:

$apcCache = $this->container->get('doctrine_cache.providers.my_apc_cache');
$arrayCache = $this->container->get('doctrine_cache.providers.my_array_cache');

Usage Example for MongoDb:

In Your Config File

// config.yml

        cache_categories: classifiad_category_cache
                server: mongodb://%mongodb_host%:%mongodb_port%
                database_name: %mongodb_database%

In Your Controller

// Saving Cached Data
$CategoryCacheProvider = $this->container->get('doctrine_cache.providers.classifiad_category_cache');
$CategoryCacheProvider->save('cache_categories', $categories, 60 * 60);

// Fetching Cached Data
$CategoryCacheProvider = $this->container->get('doctrine_cache.providers.classifiad_category_cache');
if ($CategoryCacheProvider->fetch('cache_categories')) {
    $categories = $CategoryCacheProvider->fetch('cache_categories');