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 Engine Laravel Package

byjg/cache-engine

byjg/cache-engine is a flexible PHP caching library with a consistent API and pluggable backends like Redis, Memcached, APCu, files, and databases. It makes adding portable, fast caching to PHP and Laravel applications straightforward.

View on GitHub
Deep Wiki
Context7

Getting Started

byjg/cache-engine is not a Laravel package — there's no service provider, no auto-discovery, no facade. It's a framework-agnostic PSR-6 + PSR-16 implementation that you wire up yourself. Install it and read the driver table in the README before anything else, because the driver list is the package's value proposition.

composer require byjg/cache-engine

Before you install: audit whether you actually need it. Laravel already ships file, database, Redis, Memcached, array, and DynamoDB stores. You want this package when:

  1. A third-party library type-hints Psr\Cache\CacheItemPoolInterface (PSR-6) and Laravel's Repository doesn't implement it.
  2. You're sharing a cache layer between a Laravel app and a non-Laravel service (CLI tool, worker, legacy app) and want one portable config.
  3. You need a driver Laravel doesn't have — notably the single-file store, which is handy for tiny deployments where a full filesystem cache directory is overkill.

First use case — bind a PSR-16 instance so an injected library stops spinning its own cache:

// app/Providers/CacheEngineServiceProvider.php
use ByJG\Cache\Factory;
use Psr\SimpleCache\CacheInterface;

public function register(): void
{
    $this->app->singleton(CacheInterface::class, function ($app) {
        return Factory::createInstance(
            config('cache-engine.driver'),   // e.g. 'redis', 'filesystem', 'array'
            config('cache-engine.params')    // driver-specific array
        );
    });
}

Start with the array driver and confirm your call sites work before pointing it at Redis. The package's driver constants and parameter keys vary by version — copy them verbatim from the README rather than guessing, and pin the version in composer.json.

Implementation Patterns

1. Config file per driver, not per call site. Create config/cache-engine.php with driver + params and read it only in the service provider. Every other class should type-hint the PSR interface, never the concrete pool. This is what lets you rip the package out later.

2. Adopt it into the facade via a custom Store. If you want Cache::store('cache_engine')->get(...) to work, implement Illuminate\Contracts\Cache\Store as a thin delegate to the PSR-16 instance and register it:

Cache::extend('cache_engine', function ($app) {
    return Cache::repository(new Psr16Store($app->make(CacheInterface::class)));
});

Now the helper, the facade, and event/failure hooks behave normally while the backing store is the package. Watch the TTL unit conversion here — see Gotchas.

3. Namespaced key builder. PSR-16 has no tag support and no namespace concept. Inject a small CacheKeys service that prefixes app:feature:. This is your only defence against collisions when two subsystems share one Redis database.

4. One pool per subsystem when semantics differ. Use a separate filesystem path or key prefix for ephemeral caches (rendered fragments, API responses) vs. long-lived ones (settings, computed lookups), so you can flush one without nuking the other.

5. Inject the interface, swap in tests. Bind the array driver under APP_ENV=testing in phpunit.xml. Because you bound a singleton, values leak between tests — flush in setUp() or rebind per test.

6. Long-running workers (Octane, Horizon). Register as singleton so you don't reconnect per resolve, but use scoped if your driver holds per-request state. Anything holding a socket needs a plan for reconnect after Redis timeouts.

7. PSR-6 usage pattern. Always check the hit flag — getItem() returns a fresh miss item rather than null:

$item = $pool->getItem($key);
if (!$item->isHit()) {
    $item->set($this->expensiveLookup())->expiresAfter(3600);
    $pool->save($item);
}
return $item->get();

8. Migration tip. Run both backends in parallel behind a wrapper that reads from Laravel's cache and writes to both, then cut over. There's no shared key format, so a straight swap is a cold cache.

Gotchas and Tips

  • PSR-16 reserved characters. { } ( ) / \ @ : are illegal in keys and the implementation is entitled to throw InvalidArgumentException. Laravel's cache is far more forgiving, so code migrated from Cache::put("user/{$id}/profile") will blow up. Hash or slug key segments.
  • Key length. Memcached caps at 250 bytes; the filesystem driver may have path-length limits. Prefixing plus long IDs gets you there faster than you'd think.
  • TTL semantics are inverted from Laravel. In PSR-16 a TTL of 0 or negative means delete immediately. In Laravel, 0/null means forever. This is the single most common bug when adapting code — normalize in one place, ideally in your adapter store.
  • PSR-6 hasItem() is a trap. Some drivers answer it without an actual read, and stale/expired entries can report inconsistently. Trust getItem()->isHit().
  • PSR-6 increment/decrement are explicitly non-atomic per the spec. Don't build rate limiters or counters on them; use Redis primitives.
  • No tags, no Cache::tags(), no remember(). If your app leans on tag flushing, this package will not replace Laravel's cache — run it alongside.
  • Serialization is a deploy hazard. Values are serialized; changing a class's shape (or removing it) turns cached payloads into unserialize() failures. Bake a schema version into your key prefix and bump it on breaking changes.
  • Filesystem driver. Path must be writable by the PHP user and the queue user — a difference that only shows up in production. Directory creation may not be recursive in all versions; pre-create the directory in your deploy script.
  • Single-file driver writes everything to one file. It's fine for small, low-write caches and a contention point under concurrent writes. Don't put session data there.
  • Extension requirements. Redis and Memcached drivers need ext-redis / ext-memcached and the corresponding client library. Confirm which client the Redis driver expects (phpredis vs predis) — they are not interchangeable, and the mismatch surfaces as a class-not-found at runtime, not at boot.
  • Silent failures. save() returns bool and nobody checks it. A full disk or evicted Memcached entry looks identical to success. Log false returns in staging at minimum.
  • Debugging approach. Reproduce with the array driver first to isolate logic bugs from driver bugs, then switch drivers. If it only fails under array, it's your TTL or key handling, not the backend.
  • Ecosystem risk. 11 stars, zero dependents, one maintainer. Pin an exact version ("byjg/cache-engine": "5.x.y"), commit the lockfile, and keep every call site behind Psr\SimpleCache\CacheInterface / Psr\Cache\CacheItemPoolInterface so replacing it with a three-line Laravel adapter is a one-file change.
  • Extension point. There's no plugin registry — the Factory is the only entry. To add a driver, either wrap the Factory in your own resolver that returns your implementation for unknown names, or implement CacheItemPoolInterface yourself and register it in your container alongside the package's.
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.
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
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
cgv/localized-resource