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

Php Cache Laravel Package

chillerlan/php-cache

A lightweight PSR-16 caching library for PHP offering pluggable storage adapters for Memcached, Redis, filesystem, and in-memory caches. Supports TTLs, namespacing, and simple key-value storage with minimal setup.

Deep Wiki
Context7

Getting Started

chillerlan/php-cache is a small, dependency-light PSR-16 implementation. It gives you a CacheInterface you can type-hint, plus a handful of drivers (memory, file, session, Redis, Memcached, null). There is no container, no event system, and no PSR-6 pooling — it is deliberately a thin layer over PHP’s cache primitives.

Install it with Composer:

composer require chillerlan/php-cache

The namespace is chillerlan\SimpleCache. If you only remember one thing, remember this: code against Psr\SimpleCache\CacheInterface, not against a concrete driver. That keeps the driver swappable between environments and tests.

First use case — an in-memory cache for a request or a test:

use Psr\SimpleCache\CacheInterface;
use chillerlan\SimpleCache\MemoryCache;

$cache = new MemoryCache;

$cache->set('greeting', 'hello', 60);
echo $cache->get('greeting', 'default'); // hello

For a real application, the file driver is the usual entry point:

use chillerlan\SimpleCache\FileCache;

$cache = new FileCache([
    'filestorage' => __DIR__ . '/storage/cache',
]);

Where to look first:

  1. The driver classes in src/ — MemoryCache, FileCache, SessionCache, RedisCache, MemcachedCache, NullCache.
  2. Each driver’s settings/options class (chillerlan packages use a settings container). That is the authoritative list of option keys such as storage paths or connection details.
  3. The PSR-16 interface itself. Since this package implements a standard, the interface is the contract you should design around; the package is mostly an implementation detail.

Bind it in Laravel’s container so application code never constructs drivers directly:

// AppServiceProvider::register()
$this->app->singleton(CacheInterface::class, function () {
    return new FileCache([
        'filestorage' => storage_path('framework/cache/chillerlan'),
    ]);
});

Implementation Patterns

Cache-aside with a sentinel

PSR-16’s get() default value cannot distinguish “missing” from “stored null”. Use a sentinel object:

final class Miss {}

function remember(CacheInterface $cache, string $key, int $ttl, Closure $resolve): mixed
{
    $miss  = new Miss;
    $value = $cache->get($key, $miss);

    if ($value !== $miss) {
        return $value;
    }

    $value = $resolve();
    $cache->set($key, $value, $ttl);

    return $value;
}

This is the workhorse pattern: read, miss, compute, write, return.

Environment-specific drivers

Use the same interface everywhere and swap the implementation per environment:

  • Tests → MemoryCache (fast, isolated per process) or NullCache (always misses, disables caching entirely).
  • Single-server apps / CLI → FileCache.
  • Multi-server / shared cache → RedisCache or MemcachedCache.
  • Request-scoped deduplication → SessionCache or MemoryCache.

Because everything is CacheInterface, this can be a one-line binding change.

Key namespacing

PSR-16 has no tags, hierarchies, or prefix option. Encode structure in the key yourself:

$key = sprintf('user:%d:profile:%d', $userId, $version);

Reserved characters in PSR-16 keys are { } ( ) / \ @ :, and implementations may enforce a 64-character limit. Avoid raw user input in keys; hash or slugify it.

Bulk warm and bulk read

Use setMultiple() and getMultiple() instead of loops when priming a page:

$cache->setMultiple([
    'home:stats'   => $stats,
    'home:popular' => $popular,
], 300);

$values = $cache->getMultiple(['home:stats', 'home:popular'], null);

Group invalidation by version stamp

If you need to invalidate “all user profile entries”, store a version counter and bake it into keys:

$version = $cache->get('user:profile:version', 1);

$key = "user:profile:v{$version}:{$userId}";

// invalidate the whole group:
$cache->set('user:profile:version', $version + 1);

Old entries become unreachable and expire naturally. This is the standard workaround for PSR-16’s lack of tags.

TTL discipline

Pass integers (seconds) or DateInterval values. Be explicit about 0 and negative TTLs — PSR-16 says the item should be deleted, but confirm driver behavior. Prefer named constants or a small helper so TTLs don’t become magic numbers scattered across the codebase.

Gotchas and Tips

  • No tags, no atomic increments, no locks. PSR-16 is intentionally minimal. If you need increment(), tag flushing, or stampede protection, you need a different abstraction or must build it yourself.
  • get() null ambiguity. Stored null and a cache miss look the same with a null default. Use has() or the sentinel pattern above.
  • File cache permissions and cleanup. The storage directory must exist and be writable by the PHP user. Watch out for expired-file garbage collection, disk growth, and concurrency on shared filesystems.
  • Redis/Memcached construction. These drivers need an existing client or connection options; connection failures typically surface as cache exceptions. Decide whether your app should fail-open (log and continue) or fail-closed.
  • clear() can be dangerous on shared stores. On Redis it may flush a database. Use a dedicated Redis database or instance for this cache; PSR-16 offers no built-in key prefix.
  • Key validation differs by driver. A key that works in MemoryCache may be rejected by a stricter backend. Validate and normalize keys in one place.
  • Serialization limits. File and network drivers serialize values. Store scalars and arrays where possible; avoid closures, resources, and large object graphs. Object schema changes can deserialize into broken state — version your keys when value shapes change.
  • Settings typos can be silent. chillerlan settings containers validate against declared properties; a misspelled option may be ignored or throw depending on configuration. Check the driver’s settings class rather than guessing option names.
  • Small community, small surface. With a low star count, treat the source as documentation. Pin the version in composer.json, read the driver you use, and remember it is a thin layer — forking or writing a custom driver against CacheInterface is cheap.
  • Extension point. Implement Psr\SimpleCache\CacheInterface or extend the package’s base cache class for custom backends (APCu, DynamoDB, etc.). Keep the same key/TTL conventions so the rest of your code doesn’t care.
  • Test with NullCache. It is useful for asserting that code paths do not depend on cache hits, and for disabling caching in integration tests without changing application wiring.
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