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

thecodingmachine/cache-utils

Small set of PHP cache helpers by TheCodingMachine: adapters and utilities around PSR-6/PSR-16 caches, including cache wrappers and simple tooling to standardize access, reduce boilerplate, and ease integration in frameworks and libraries.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require thecodingmachine/cache-utils
    

    No Laravel-specific configuration is required—this package is framework-agnostic.

  2. Basic Usage Inject the CacheUtils service into your Laravel service container:

    use TheCodingMachine\Cache\CacheUtils;
    use Psr\Cache\CacheItemPoolInterface;
    
    // In a service provider (e.g., AppServiceProvider)
    $this->app->bind(CacheUtils::class, function ($app) {
        return new CacheUtils($app->make(CacheItemPoolInterface::class));
    });
    
  3. First Use Case: Safe Cache Retrieval

    use TheCodingMachine\Cache\CacheUtils;
    
    class MyService {
        private $cacheUtils;
    
        public function __construct(CacheUtils $cacheUtils) {
            $this->cacheUtils = $cacheUtils;
        }
    
        public function getCachedData(string $key, callable $callback) {
            return $this->cacheUtils->get($key, $callback, 3600); // Cache for 1 hour
        }
    }
    

Implementation Patterns

1. Cache Key Generation

Use CacheUtils to generate consistent, namespaced keys:

$key = $cacheUtils->getKey('my_namespace', 'dynamic_key', ['param1', 'param2']);
// Output: "my_namespace:dynamic_key:param1:param2"

Laravel Integration Tip: Combine with Laravel’s cache tags for invalidation:

$key = $cacheUtils->getKey('laravel:user', $userId);
Cache::tags(['user:' . $userId])->put($key, $data, 3600);

2. Safe Cache Operations

Atomic get/set with fallback:

$data = $cacheUtils->get('expensive_data', function () {
    return $this->fetchExpensiveData();
}, 3600);

Conditional updates:

$cacheUtils->updateIf('user:profile', function ($item) {
    $item->set($this->updateProfileData());
}, 3600, function ($item) {
    return $item->isHit();
});

3. Cache Invalidation

Tag-based invalidation (Laravel-specific):

$cacheUtils->invalidateTag('user:profile'); // Clears all keys tagged with "user:profile"

Wildcard invalidation:

$cacheUtils->invalidate('user:*'); // Clears all user-related keys

4. Composing with Laravel’s Cache

Wrap Laravel’s cache in CacheUtils for consistency:

$cacheUtils = new CacheUtils(Cache::store('array')); // Or any PSR-16 adapter

Use with Laravel’s Cache::remember alternative:

$data = $cacheUtils->remember('key', 3600, function () {
    return Model::query()->first();
});

Gotchas and Tips

1. Key Collisions

  • Pitfall: Custom key generation may clash with Laravel’s default keys.
  • Fix: Prefix keys explicitly:
    $key = $cacheUtils->getKey('laravel:', 'my_key');
    

2. Cache Adapter Compatibility

  • Pitfall: Not all PSR-16 adapters support tags (e.g., file driver).
  • Tip: Use Cache::store('redis') or Cache::store('database') for tag support.

3. Debugging Missed Cache Hits

  • Tip: Enable PSR-16 cache logging:
    Cache::store('array')->setLogger(new \Monolog\Logger('cache'));
    

4. Extension Points

  • Custom Key Strategies: Extend CacheUtils to add namespaces:
    $cacheUtils = new CacheUtils($cachePool, 'my_app:');
    
  • Middleware: Add pre/post-cache hooks via CacheUtils::addListener().

5. Laravel-Specific Quirks

  • Tag Invalidation: Laravel’s Cache::tags() is not PSR-16 compliant. Use CacheUtils for cross-adapter consistency.
  • Serialization: Ensure cached data is serializable (Laravel’s Cache handles this, but raw PSR-16 may not).

6. Performance

  • Tip: Batch operations with CacheUtils::batchGet() to reduce round trips:
    $keys = ['key1', 'key2'];
    $results = $cacheUtils->batchGet($keys);
    
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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator