Weave Code
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 Laravel Package

sonata-project/cache

Deprecated Sonata cache library providing adapters for cache backends and counters. Includes Redis (PRedis) implementations to set/get cached values and increment counters, with simple key arrays and TTL support via Composer install.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require sonata-project/cache
    

    Ensure predis/predis (for Redis) or ext-memcached (for Memcached) is installed.

  2. Basic Cache Usage:

    use Sonata\Cache\Adapter\Cache\PRedisCache;
    
    $adapter = new PRedisCache([
        'host' => '127.0.0.1',
        'port' => 6379,
        'database' => 0,
    ]);
    
    // Set cache with multi-key support
    $keys = ['user' => 1, 'profile' => 'settings'];
    $adapter->set($keys, 'cached_data', 3600); // 1-hour TTL
    
    // Retrieve cache
    $cacheElement = $adapter->get($keys);
    $data = $cacheElement->getData(); // 'cached_data'
    
  3. Basic Counter Usage:

    use Sonata\Cache\Adapter\Counter\PRedisCounter;
    
    $counterAdapter = new PRedisCounter([
        'host' => '127.0.0.1',
        'port' => 6379,
        'database' => 0,
    ]);
    
    $counter = $counterAdapter->increment('page_views');
    $views = $counter->getValue(); // e.g., 1
    
  4. Laravel Integration (Quick Start): Bind the adapter to Laravel’s service container in AppServiceProvider:

    public function register()
    {
        $this->app->singleton('sonata.cache', function ($app) {
            return new PRedisCache([
                'host' => config('cache.redis.host'),
                'port' => config('cache.redis.port'),
            ]);
        });
    }
    

Where to Look First

  • Documentation: Focus on the README.md for basic usage.
  • Source Code: Explore src/Adapter/Cache/ for cache adapters and src/Adapter/Counter/ for counter logic.
  • Changelog: Review CHANGELOG.md for breaking changes (e.g., PHP 7.3+ requirement in v2.2.0).

First Use Case

Scenario: Cache user-specific settings with a composite key (e.g., user:{id}:theme).

$keys = ['user' => $userId, 'setting' => 'theme'];
$adapter->set($keys, $theme, 86400); // Cache for 1 day
$theme = $adapter->get($keys)->getData();

Implementation Patterns

Usage Patterns

1. Multi-Key Caching

  • Pattern: Use associative arrays as keys for hierarchical or composite caching.
  • Example: Cache user preferences with nested keys.
    $keys = ['user' => 123, 'preferences' => 'notifications'];
    $adapter->set($keys, $prefs, 3600);
    
  • Laravel Integration: Serialize keys for Laravel’s single-key cache:
    $serializedKey = json_encode($keys);
    Cache::put($serializedKey, $data, 3600);
    

2. Counter Integration

  • Pattern: Use counters for analytics, rate limiting, or tracking.
  • Example: Track API request counts.
    $counter = $counterAdapter->increment('api_requests');
    $requestCount = $counter->getValue();
    
  • Laravel Facade: Wrap counters in a custom facade:
    // app/Facades/Counter.php
    public static function increment($key, $value = 1)
    {
        return app('sonata.counter')->increment($key, $value);
    }
    

3. Adapter Switching

  • Pattern: Swap Redis/Memcached backends by changing the adapter class.
  • Example: Replace PRedisCache with MemcachedCache (if supported).
    $adapter = new Sonata\Cache\Adapter\Cache\MemcachedCache([
        'host' => '127.0.0.1',
        'port' => 11211,
    ]);
    

4. TTL Management

  • Pattern: Dynamically set TTLs based on data volatility.
  • Example: Short TTL for volatile data (e.g., 60 seconds).
    $adapter->set($keys, $data, 60);
    

5. Bulk Operations

  • Pattern: Use batch operations for performance (if supported).
  • Example: Set multiple keys at once (not natively supported; implement manually).
    foreach ($data as $keys => $value) {
        $adapter->set($keys, $value, 3600);
    }
    

Workflows

Cache Workflow

  1. Set Data: Use set($keys, $data, $ttl) for multi-key caching.
  2. Retrieve Data: Use get($keys)->getData() to fetch cached values.
  3. Check Existence: Use has($keys) to verify cache presence.
  4. Delete Data: Use delete($keys) to remove cached entries.

Counter Workflow

  1. Increment: Use increment($key, $value = 1) to increase a counter.
  2. Get Value: Use $counter->getValue() to retrieve the current count.
  3. Decrement: Manually subtract from the value (no native decrement method).

Integration Tips

Laravel Cache Store

Extend Laravel’s CacheStore to use Sonata’s adapter:

// app/Providers/AppServiceProvider.php
use Sonata\Cache\Adapter\Cache\PRedisCache;
use Illuminate\Cache\Repository;

public function register()
{
    $this->app->bind('sonata.cache', function () {
        return new PRedisCache([
            'host' => config('cache.redis.host'),
            'port' => config('cache.redis.port'),
        ]);
    });

    $this->app->extend('cache.store', function ($app, $store) {
        if ($store === 'sonata') {
            return new Repository($app['sonata.cache']);
        }
        return $store;
    });
}

Configure in .env:

CACHE_DEFAULT=sonata

PSR-3 Logging

Configure logging via the adapter’s constructor:

use Psr\Log\LoggerInterface;

$adapter = new PRedisCache([
    'host' => '127.0.0.1',
    'logger' => $this->app->make(LoggerInterface::class),
]);

Key Serialization

For Laravel’s single-key cache, serialize multi-keys:

$serializedKey = json_encode($keys);
Cache::put($serializedKey, $data, $ttl);

Error Handling

Wrap adapter calls in try-catch blocks:

try {
    $data = $adapter->get($keys)->getData();
} catch (\Exception $e) {
    Log::error("Cache error: " . $e->getMessage());
    // Fallback logic
}

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • Risk: No future updates or security patches. Avoid for new projects.
    • Mitigation: Plan to migrate to a maintained alternative (e.g., Symfony Cache, Predis).
  2. PHP Version Requirement:

    • Issue: Requires PHP 7.3+ (since v2.2.0). Older Laravel versions (e.g., 5.x) may not be compatible.
    • Mitigation: Use a fork or downgrade to v2.1.x if needed.
  3. Multi-Key Limitations:

    • Issue: Laravel’s cache expects scalar keys. Multi-key arrays must be serialized manually.
    • Mitigation: Use json_encode($keys) for serialization/deserialization.
  4. No Native Laravel Integration:

    • Issue: No built-in support for Laravel’s Cache facade or service provider.
    • Mitigation: Create custom bindings (as shown in Implementation Patterns).
  5. Counter Limitations:

    • Issue: No native decrement method or atomic operations for complex counters.
    • Mitigation: Implement custom logic or use Lua scripts in Redis.
  6. Predis/Memcached Dependencies:

    • Issue: Requires predis/predis or ext-memcached, which may not be installed.
    • Mitigation: Ensure dependencies are included in composer.json and installed in deployment.
  7. Key Collisions:

    • Issue: Multi-key arrays with similar structures may collide when serialized.
    • Mitigation: Use unique prefixes in keys (e.g., user:{id}:{setting}).
  8. TTL Granularity:

    • Issue: TTL is set per key
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui