PHPackages                             emag/cache-bundle - 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. emag/cache-bundle

Abandoned → [emag-tech-labs/annotation-cache-bundle](/?search=emag-tech-labs%2Fannotation-cache-bundle)Library[Caching](/categories/caching)

emag/cache-bundle
=================

CacheBundle by eMAGTechLabs

4.2.0(7y ago)1916.5k5[2 PRs](https://github.com/eMAGTechLabs/cache-bundle/pulls)MITPHPPHP &gt;=7.0

Since May 12Pushed 3y ago19 watchersCompare

[ Source](https://github.com/eMAGTechLabs/cache-bundle)[ Packagist](https://packagist.org/packages/emag/cache-bundle)[ RSS](/packages/emag-cache-bundle/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (5)Dependencies (16)Versions (23)Used By (0)

Annotation Cache Bundle
=======================

[](#annotation-cache-bundle)

[![Packagist Version](https://camo.githubusercontent.com/ee7fde50748533d5e25e5d6c0ef7f7300b2a8c426ce765ea39327f0d0c4cec56/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f656d61672d746563682d6c6162732f616e6e6f746174696f6e2d63616368652d62756e646c65)](https://packagist.org/packages/emag-tech-labs/annotation-cache-bundle)[![Build Status](https://camo.githubusercontent.com/180b71f5ee64bf1e935aa19d1bedd0741fbd563969f19829f7f983f0e9f9e092/68747470733a2f2f7472617669732d63692e636f6d2f654d4147546563684c6162732f616e6e6f746174696f6e2d63616368652d62756e646c652e7376673f6272616e63683d6d6173746572)](https://travis-ci.com/eMAGTechLabs/annotation-cache-bundle)[![Total Downloads](https://camo.githubusercontent.com/0ec0d51a1f1354b92e83d29c80f38c3f3e83443fda78dad4bbcb1211053a8a04/68747470733a2f2f706f7365722e707567782e6f72672f656d61672d746563682d6c6162732f616e6e6f746174696f6e2d63616368652d62756e646c652f646f776e6c6f616473)](https://packagist.org/packages/emag-tech-labs/annotation-cache-bundle)[![Latest Stable Version](https://camo.githubusercontent.com/3c18c63d2e4b58c2f9f9dbdfac77db32e0eedb1c1df11cee678173e047e8db6b/68747470733a2f2f706f7365722e707567782e6f72672f656d61672d746563682d6c6162732f616e6e6f746174696f6e2d63616368652d62756e646c652f762f737461626c65)](https://packagist.org/packages/emag-tech-labs/annotation-cache-bundle)[![License](https://camo.githubusercontent.com/51568128afe503ff172314959874443f9221594d292a2099a9d74b390338913b/68747470733a2f2f706f7365722e707567782e6f72672f656d61672d746563682d6c6162732f616e6e6f746174696f6e2d63616368652d62756e646c652f6c6963656e7365)](https://github.com/emag-tech-labs/annotation-cache-bundle/blob/master/LICENSE)[![Coverage Status](https://camo.githubusercontent.com/711a9d068d4073128fad7357c87ecaf4a4faa731c9ecffbe1ff9fbf048644507/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f654d4147546563684c6162732f616e6e6f746174696f6e2d63616368652d62756e646c652f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/eMAGTechLabs/annotation-cache-bundle?branch=master)

---

Annotation based caching for method responses in services inside a Symfony container.

This bundle helps you to add caching with a simple annotation or attribute. You can store the cache in any class that implements PSR-6: Caching Interface be it a simple array or a redis/memcache storage.

How it works
------------

[](#how-it-works)

This bundle will scan all the methods from the defined services and look for the Cache annotation or attribute (for PHP 8+).

For all the services where the Cache annotation/attribute is found, it will create a proxy class (using ocramius/proxy-manager) that extends the service class, include the CacheableClassTrait and overwrite the methods that have the Cache annotation/attribute.

The overwritten methods consist of a call to the `getCached` method that identifies the annotation details, gets the key, gets the Cache PSR-6 implementation and then gets the result from cache. If no data with the generated cache key is found, it will call the original method and then save the response in the given provider.

The bundle has a CompilerPass implementation that will search and overwrite the service definition with the proxy class created in the process explained above.

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

[](#installation)

### With Symfony Flex

[](#with-symfony-flex)

The easiest way to install and configure the AnnotationCacheBundle with Symfony is by using [Symfony Flex](https://github.com/symfony/flex):

```
 composer require symfony/flex ^1.0
 composer config extra.symfony.allow-contrib true
 composer require emag-tech-labs/annotation-cache-bundle
```

Symfony Flex will automatically register and configure the bundle.

### Without Symfony Flex

[](#without-symfony-flex)

If your application does not use Symfony Flex you can configure the bundle manually by following the steps below

#### Step 1: Download the bundle

[](#step-1-download-the-bundle)

Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:

```
composer require emag-tech-labs/annotation-cache-bundle
```

#### Step 2: Enable the bundle

[](#step-2-enable-the-bundle)

Then, enable the bundle by adding it to the list of registered bundles in the `config/bundles.php` file of your project:

```
// config/bundles.php

return [
    // ...
    EmagTechLabs\AnnotationCacheBundle\AnnotationCacheBundle::class => ['all' => true],
];
```

#### Step 3: Configuration

[](#step-3-configuration)

The easiest way is to dump the config and copy it to `configs/packages/emag_annotation_cache.yaml`.

```
bin/console config:dump-reference AnnotationCacheBundle
```

##### Configuration example

[](#configuration-example)

You have to configure the name of the service that is PSR6 compliant, that means it will have to implement `Psr\Cache\CacheItemPoolInterface`:

```
# app/config/services.yaml

services:
    cache.array:
        class: Symfony\Component\Cache\Adapter\ArrayAdapter
    cache.redis:
        class: Symfony\Component\Cache\Adapter\RedisAdapter
        arguments: ['@predis']
```

```
#configs/packages/emag_annotation_cache.yaml

# Annotation Cache Bundle
annotation_cache:
    provider:
        default: cache.redis
        array: cache.array
    ignore_namespaces:
      - 'Symfony\\'
      - 'Doctrine\\'
    ignore_names:
      - legacy
      - type
      - required
```

Usage
-----

[](#usage)

Add the `Cache` annotation for the methods you want to cache.

Annotation parameters:

- `cache` - cache prefix, **string**, *default value: null* (eg: 'my\_custom\_prefix\_')
- `key` - name of argument(s) to include in cache key hash generation, **string, arg name separated by a comma**, *default value: ''* (eg: 'a,b')
- `ttl` - time to store the cache in seconds, **int**, *default value: 600* (eg: '3600')
- `reset` - if the cache should be reset or not, **boolean**, *default value: false* (eg: 'true')
- `storage` - if multiple providers are defined, you can specify which provider to use, **string**, *default value: 'default'* (eg: 'array')

### Annotations defined with Doctrine Annotations library

[](#annotations-defined-with-doctrine-annotations-library)

```
use EmagTechLabs\AnnotationCacheBundle\Annotation\Cache;

/**
 * @Cache(cache="", [key="",  [ttl=600, [reset=true, [storage=default ]]]])
 */
```

#### Example

[](#example)

```
namespace AppCacheBundle\Service;

use EmagTechLabs\AnnotationCacheBundle\Annotation\Cache;

class AppService
{
    /**
     * @Cache(cache="app_high_cpu", ttl=60)
     *
     * @return int
     */
    public function getHighCPUOperation(): int
    {
        sleep(10); // 'Simulate a time consuming operation';
        return 20;
    }
}
```

### Annotations defined with PHP 8 attributes

[](#annotations-defined-with-php-8-attributes)

```
use EmagTechLabs\AnnotationCacheBundle\Annotation\Cache;

 #[Cache(cache:'', key:'', ttl:600, reset: true, storage: 'default')]
```

#### Example

[](#example-1)

```
namespace AppCacheBundle\Service;

use EmagTechLabs\AnnotationCacheBundle\Annotation\Cache;

class AppService
{
    #[Cache(cache:'app_high_cpu', ttl: 60)]
    public function getHighCPUOperation(): int
    {
        sleep(10); // 'Simulate a time consuming operation';
        return 20;
    }
}
```

### Use cases

[](#use-cases)

Below you can find two ways you can use this Bundle

#### Config

[](#config)

```
# app/config/services.yaml

services:
    cache.array:
        class: Symfony\Component\Cache\Adapter\ArrayAdapter
    cache.redis:
        class: Symfony\Component\Cache\Adapter\RedisAdapter
        arguments: ['@predis']
```

```
#configs/packages/emag_annotation_cache.yaml

# Annotation Cache Bundle
annotation_cache:
    provider:
        default: cache.array
        redis: cache.redis
    ignore_namespaces:
      - 'Symfony\\'
```

#### Service Code

[](#service-code)

This bundle can be used in multiple ways, two of them are shown below.

The first case is the most common one, where you have a method that does multiple time-consuming operations, and you want to cache the response in redis with a prefix (simple\_time\_consuming\_operation\_) for a given time (60s in the case below). The logic here is to look for the value in redis, and if not found, run the actual method, get the result and cache it for further use taking into account the arguments passed in the `@Cache` annotation.

The second case could be used if you want to generate the cache in a command and have it already warmed up, or maybe update the cache when a certain event is triggered, or you update the information in a database. Based on the example below, you could set a cron to run every ~3000 seconds and that will recreate the cache before it expires. Because we are using the same cache prefix and keys, when the same argument values are passed for both methods(`getTimeConsumingOperationValueWithReset`and `getTimeConsumingOperationValue`), the generated cache key will be the same, in this case: time\_consuming\_operation\_7fe49b314fb356bee76dbd3b8716b4d5ab5db600. That means that both methods will write (and read) the cache in (from) the same cache key. Because the second method has the `reset` argument set to true, any call to the second method will overwrite the cache value in the key time\_consuming\_operation\_7fe49b314fb356bee76dbd3b8716b4d5ab5db600 with the new result of the function.

```
namespace AppCacheBundle\Service;

use EmagTechLabs\AnnotationCacheBundle\Annotation\Cache;

class AppService
{
    /**
     * @Cache(cache="simple_time_consuming_operation_", ttl=60, storage="redis")
     *
     * @param int $a
     * @param int $b
     *
     * @return int
     */
    public function getSimpleTimeConsumingOperationValue(int $a, int $b): int
    {
        sleep(10); // 'Simulate a time consuming operation';
        return $a + $b;
    }

    #[Cache(cache:'time_consuming_operation_', key: 'a,b', ttl: 3600, storage: 'redis')]
    public function getTimeConsumingOperationValue(int $a, int $b): int
    {
        return $this->getTimeConsumingOperationValueWithReset($a, $b);
    }

    #[Cache(cache:'time_consuming_operation_', key: 'a,b', ttl: 3600, reset: true, storage: 'redis')]
    public function getTimeConsumingOperationValueWithReset(int $a, int $b): int
    {
        sleep(10); // 'Simulate a time consuming operation';
        return $a + $b;
    }
}
```

#### Service calls

[](#service-calls)

```
// from controller
/** AppService $appService */
$appService->getTimeConsumingOperationValue(1, 2);

// from command
/** AppService $appService */
$appService->getTimeConsumingOperationValueWithReset(1, 2);
```

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

[](#contributing)

Thanks for your interest in contributing! There are many ways to contribute to this project. Get started [here](CONTRIBUTING.md).

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity30

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 68.8% 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 ~46 days

Recently: every ~164 days

Total

20

Last Release

2783d ago

Major Versions

1.1.1 → 2.0.02016-10-18

v1.x-dev → 3.0.02016-12-07

v3.x-dev → 4.0.02017-01-08

PHP version history (2 changes)1.0.0PHP &gt;=5.5

3.0.0PHP &gt;=7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/4bac1055107b4c34bf3d19024144c4d3b96552ec8e4a9fa1cb362f385bb29f63?d=identicon)[skafandri](/maintainers/skafandri)

![](https://www.gravatar.com/avatar/39eb00e570469bdff93ae4a0d6aa3fe6698d443e622c36784cfb5aded8ee9019?d=identicon)[emagtechlabsadmin](/maintainers/emagtechlabsadmin)

![](https://www.gravatar.com/avatar/253588ba44ff31963b43f069a068166473031b008cf401f5a71749ee3d697e21?d=identicon)[danieltoader](/maintainers/danieltoader)

![](https://www.gravatar.com/avatar/c1df8239dc80f4f97dd741957303ecb73c1fdc2379c05a06ce2868e71e57e76c?d=identicon)[alex.bumbacea](/maintainers/alex.bumbacea)

---

Top Contributors

[![alexbumbacea](https://avatars.githubusercontent.com/u/724634?v=4)](https://github.com/alexbumbacea "alexbumbacea (53 commits)")[![danieltoader](https://avatars.githubusercontent.com/u/1113017?v=4)](https://github.com/danieltoader "danieltoader (15 commits)")[![devrck](https://avatars.githubusercontent.com/u/16414298?v=4)](https://github.com/devrck "devrck (7 commits)")[![Belibov](https://avatars.githubusercontent.com/u/15921824?v=4)](https://github.com/Belibov "Belibov (2 commits)")

---

Tags

annotationscachecache-annotationphpsymfonysymfony-bundle

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/emag-cache-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/emag-cache-bundle/health.svg)](https://phpackages.com/packages/emag-cache-bundle)
```

###  Alternatives

[symfony/cache

Provides extended PSR-6, PSR-16 (and tags) implementations

4.2k348.9M2.5k](/packages/symfony-cache)[nelmio/api-doc-bundle

Generates documentation for your REST API from attributes

2.3k63.6M233](/packages/nelmio-api-doc-bundle)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)

PHPackages © 2026

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