Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cache Bundle Laravel Package

rmzamora/cache-bundle

rmzamora/cache-bundle is a Laravel package that bundles common caching helpers and configuration into a single installable provider, aiming to simplify cache setup and reuse across projects. Check the repository for supported features and usage.

View on GitHub
Deep Wiki
Context7

Getting Started

Read this first: rmzamora/cache-bundle is a fork of SonataCacheBundle, which means it is a Symfony bundle, not a Laravel package. There is no service provider, no config/cache-bundle.php, no facade, and no Illuminate\Contracts\Cache binding. Archived, 0 stars, 0 dependents, no maintenance. Plan accordingly: for a Laravel app, the correct "first use case" is to not install it and use Cache::remember() instead. The only realistic reason to open this repo is to read (MIT-licensed) adapter code you can vendor.

Where to look first in the source tree:

  1. composer.json — package name, PHP constraint, and the hard deps (symfony/http-kernel, symfony/dependency-injection, symfony/config, sonata-project/cache). This tells you immediately whether it will even install on your PHP version.
  2. DependencyInjection/Configuration.php + SonataCacheExtension.php — the entire config surface (sonata_cache.cache.* adapters, sonata_cache.esi).
  3. Adapter/ — MemcachedAdapter, MongoAdapter, RedisAdapter, PredisAdapter, NoopAdapter, SymfonyAdapter. These are small, readable classes around Sonata\Cache\CacheAdapterInterface.
  4. CacheManager.php / the sonata-project/cache CacheElement class — the actual get/put/flush API.

Minimal wiring, if you are on a legacy Symfony app:

composer require rmzamora/cache-bundle:"^3.x"   # pin it, commit the lock
// config/bundles.php
return [ Sonata\CacheBundle\SonataCacheBundle::class => ['all' => true] ];
# config/packages/sonata_cache.yaml
sonata_cache:
    cache:
        memcached:
            servers:
                - { host: 127.0.0.1, port: 11211, weight: 1 }
        redis:
            servers:
                - { host: 127.0.0.1, port: 6379, database: 3 }
// first use case: cache an expensive external API payload with a TTL
$manager = $this->get('sonata.cache.memcached');   // or ->get('sonata.cache.redis')
$element = new \Sonata\Cache\CacheElement('weather:paris', 3600);

$value = $manager->get($element);
if ($value === false) {
    $value = $this->weatherClient->fetch('paris');   // expensive
    $manager->put($element, $value);
}

The Laravel equivalent is one line, which is the whole story:

$value = Cache::remember('weather:paris', 3600, fn () => $this->weatherClient->fetch('paris'));

Implementation Patterns

1. CacheElement + manager (manual get-or-set). The bundle deliberately does not give you a remember() helper — you write the hit/miss branch yourself. TTL lives on the element (setTtl()), not on the manager. Keep a small private helper so you never forget the put:

private function cached(string $key, int $ttl, callable $compute)
{
    $element = new CacheElement($key, $ttl);
    $value   = $this->cacheManager->get($element);
    if ($value === false) {
        $this->cacheManager->put($element, $value = $compute());
    }
    return $value;
}

2. Deterministic, derived keys. Because flush() needs the exact element list (see Gotchas), keys must be reconstructible from data, not random. Pattern: sprintf('%s:%s:v%d', $namespace, $entity->getId(), $schemaVersion).

3. flush() with an explicit list. CacheManager::flush(array $keys) takes concrete CacheElement objects. It is not a namespace or wildcard flush. Callers typically build them from the same key-generation function used on write.

4. NoopAdapter for dev/test. Swap sonata.cache.memcached → sonata.cache.noop per environment (or bind a test container alias). This is the cleanest way to get deterministic tests.

5. ESI fragments — the one place this bundle earns its keep. sonata.cache.esi + EsiCacheManager works with Symfony's HttpCache to cache sub-fragments and invalidate them via a version token (sonata_cache.esi.version). Bump the version and every fragment is logically stale at once. If you are porting the idea, that token-in-the-key trick maps cleanly onto Laravel's Cache::tags() on Redis.

6. Sonata BlockBundle integration. Blocks declare a cache setting in their admin, and the block service uses the configured adapter + TTL. This is the original consumer — if you're not using BlockBundle or PageBundle, the bundle has almost nothing left to offer.

7. Porting the adapter seam to Laravel. The reusable idea is CacheAdapterInterface (get / put / flush / isContextualized) as a thin port. If you must keep the semantics, wrap the backend behind your own interface and back it with Laravel's repository rather than pulling Symfony in:

final class SonataStyleCache
{
    public function __construct(private \Illuminate\Contracts\Cache\Repository $store) {}

    public function get(CacheElement $e)  { return $this->store->get($e->getKey(), false); }
    public function put(CacheElement $e, $v) { $this->store->put($e->getKey(), $v, $e->getTtl()); }
    public function flush(array $elements)   {
        foreach ($elements as $e) { $this->store->forget($e->getKey()); }
    }
}

8. Serialization. Mongo and Memcached adapters store serialized payloads; anything with closures, resources, or Eloquent-ish lazy objects will blow up on read. Cache scalars and plain arrays only.

Gotchas and Tips

  • It's a Symfony bundle. composer require in a Laravel app drags in symfony/http-kernel and the DI container, and the SonataCacheBundle class will never be loaded. There is no Laravel bridge here, and none is coming — the repo is archived.
  • Zero-usage, first-generation-of-a-fork risk. 0 stars / 0 dependents / archived means no PHP 8.x guarantees. Expect failures around Bundle::getContainerExtension() deprecations, Container::get() removal, and typed signatures on memcached/redis extensions before you get anywhere.
  • sonata-project/* versioning history. Pre-4.0 these packages did not follow semver strictly; a "minor" bump has broken APIs before. Pin exact versions and lock the file.
  • flush() is not a wildcard. If you cannot reconstruct the key list, you cannot invalidate. This is the single most common production bug with this API — you end up with permanently stale entries and a cache you're afraid to touch.
  • ESI version token. If you forget to bump sonata_cache.esi.version on deploy, stale fragments survive forever. Wire the bump into your release script.
  • Adapter service-id confusion. predis vs redis (phpredis) and apc vs apcu are different service ids. Picking the wrong one fails at container compile time with a plain "service not found", which is easy to misread as a config typo elsewhere.
  • Redis database collisions. Default database: 0 will happily share a keyspace with sessions, queues, and Horizon. Use a dedicated DB index; otherwise a flush wipes unrelated data.
  • Memcached key limits. 250 bytes, no spaces/control characters. Long class-derived keys fail silently — get() returns false, you recompute every request, and it looks like "caching just doesn't work." Log your keys during bring-up.
  • No stampede protection. No mutex, no early-expiration, no probabilistic refresh. Under load, a hot key expiring means N concurrent recomputes. Modern symfony/cache (LockRegistry, EarlyExpiration) or Laravel's Cache::lock() solves this; this bundle does not.
  • Debugging is manual. There is no profiler panel. Wrap the manager in a decorator that logs key + hit/miss + duration, or run with NoopAdapter to confirm the non-cached path is correct first.
  • Extension point. Implement Sonata\Cache\CacheAdapterInterface and tag the service — that's the only sanctioned seam. In practice, writing a 40-line adapter against Laravel's Repository is cheaper than debugging this one.
  • License is your friend. MIT means you can legally copy an adapter class into your own codebase. Given the project's state, vendoring the 30 lines you need is strictly better than depending on it.
  • Migration targets. Symfony: symfony/cache (PSR-6/PSR-16), which is what upstream Sonata itself moved to. Laravel: Illuminate\Contracts\Cache\Repository, with Cache::tags() on Redis for the ESI-style grouped invalidation.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console