cache/namespaced-cache
PSR-6 cache pool decorator that adds namespaces on top of a hierarchical cache (e.g., Redis). Wrap an existing cache pool and automatically prefix keys per namespace, helping isolate apps/modules while reusing the same backend.
namespaced-cache package provides a decorator pattern to add namespace support to existing cache backends (e.g., Redis, Memcached, file-based caches). This is particularly valuable in multi-tenant SaaS applications, feature flagging systems, or modular microservices where cache isolation is critical.Illuminate\Cache) is extensible but lacks native namespace support. This package bridges that gap without requiring a full cache backend replacement.CacheStore, CacheManager), minimizing refactoring.tenant:123:user:456), enabling fine-grained cache isolation.Cache::get('tenant:X:key') where X doesn’t exist)?Cache facade and CacheManager. No changes to Laravel’s service container or configuration are needed beyond registering the decorator.redis driver)memcached driver)database driver)file driver)spatie/laravel-cache, ensure they support the underlying cache driver (e.g., Redis).Phase 1: Proof of Concept
config/cache.php:
'stores' => [
'namespaced_redis' => [
'driver' => 'namespaced',
'prefix' => 'laravel_namespaced_',
'store' => 'redis',
'namespace' => 'tenant', // Default namespace
],
'redis' => [
'driver' => 'redis',
'url' => env('REDIS_URL'),
],
],
Cache::store() calls to use the new store:
Cache::store('namespaced_redis')->get('tenant:123:key');
Phase 2: Gradual Rollout
// Helper function
function tenantCache($tenantId) {
return Cache::store('namespaced_redis')->namespace($tenantId);
}
Phase 3: Full Adoption
CacheNamespaceManager).CacheStore interface.composer.json constraints).SET/GET with namespaced keys).Cache::get(), Cache::remember()).composer.json if stability is critical.tenant:{id}:module:{name}) and enforce it via:
NamespaceValid).tenant:123:key).Cache::store('namespaced_redis')->namespace(null)->get('global_key');
Cache::store('namespaced_redis')->flush()).maxmemory-policy).| Failure Scenario | Impact | Mitigation |
|---|---|---|
| Redis/Memcached node failure | Partial namespace unavailability | Use Redis Sentinel/Memcached failover. |
| Namespace collision | Data corruption | Enforce unique namespace prefixes. |
| Cache key explosion | Memory exhaustion | Set TTLs, use remember() with namespaces. |
| Decorator bug | Silent cache corruption | Feature flag the decorator; roll back if needed. |
| Tenant isolation leak | Cross-tenant data exposure | Audit namespace usage in logs. |
README section on namespace conventions.// Get
Cache::namespace('tenant:123')->get('key');
// Set with TTL
Cache::namespace('tenant:123')->put('key', 'value', 60);
// Clear namespace
Cache::namespace('tenant:123')->flush();
tenant:user:{id} vs. tenant:{id}:all).tenant:1 and tenant:2 caches don’t interfere).How can I help you explore Laravel packages today?