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

In Memory Cache Laravel Package

beste/in-memory-cache

PSR-6 in-memory cache for PHP, ideal as a default cache or for tests. Lightweight CacheItemPool implementation with support for expiration and optional PSR-20 clock injection (e.g., frozen clocks) to control time in tests.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • PSR-6 Compliance: Aligns perfectly with Laravel’s caching abstraction (Illuminate\Contracts\Cache\Store), enabling seamless integration with the Cache facade, adapters, and third-party libraries. The package’s adherence to PSR-6 ensures compatibility with Laravel’s event system (e.g., Cache::store() events) and artisan commands (e.g., cache:clear).
  • Use Case Alignment:
    • Testing: Eliminates flaky external dependencies (Redis/Memcached) by providing a deterministic, isolated cache for unit/integration tests. Ideal for scenarios requiring consistent cache behavior across environments.
    • Fallback Mechanism: Acts as a lightweight, dependency-free fallback for production when primary caches (e.g., Redis) fail, enabling graceful degradation during outages or deployments.
    • Development/Staging: Reduces infrastructure overhead in non-production environments where persistence isn’t critical (e.g., local dev, CI/CD pipelines).
  • Laravel Synergy:
    • Supports Laravel’s Cache::remember(), Cache::put(), and Cache::get() methods when configured as a PSR-6 driver.
    • Compatible with Laravel’s cache:clear artisan command (if manually cleared).
    • Integrates with Laravel’s time package and travel() helper via PSR-20 clock support (e.g., Beste\Clock\FrozenClock).

Integration Feasibility

  • Low-Coupling Design: Zero configuration required beyond instantiation. Can be integrated into any Laravel application without modifying business logic.
  • PSR-20 Clock Integration: Enables advanced testing scenarios (e.g., frozen time for TTL assertions) via Beste\Clock\FrozenClock, aligning with Laravel’s testing best practices.
  • Thread/Process Safety:
    • Not Thread-Safe: Unsafe for multi-threaded environments (e.g., Swoole, ReactPHP). Must be scoped to a single request or process (e.g., HTTP requests, CLI commands).
    • Process-Safe: Safe within Laravel’s request lifecycle but risks memory leaks in long-running processes (e.g., queues, workers).
  • Serialization Limits: Relies on PHP’s serialize()/unserialize(), which may fail for complex objects (e.g., closures, resources). Laravel’s serialize() helper can mitigate this, but custom serialization logic may be required for edge cases.
  • Key Flexibility: Supports extended PSR-6 key validation (e.g., dashes -, arbitrary length), reducing friction for Laravel’s dynamic key generation (e.g., Cache::tags()).

Technical Risk

  • Memory Management:
    • Risk: In-memory cache grows indefinitely without TTL or manual cleanup, leading to memory bloat in long-running processes (e.g., Laravel queues, CLI scripts).
    • Mitigation:
      • Enforce strict TTLs (e.g., Cache::put('key', 'value', now()->addMinutes(1))).
      • Implement manual cleanup (e.g., Cache::forget() or Cache::clear()) in critical paths.
      • Avoid use in persistent processes (e.g., queues) unless paired with aggressive TTLs.
  • Performance:
    • Risk: Slower than Redis/Memcached for high-throughput scenarios due to PHP’s in-memory overhead.
    • Mitigation: Reserve for non-critical paths (e.g., testing, fallbacks) where performance isn’t a bottleneck.
  • PHP Version Dependency:
    • Risk: Requires PHP 8.3+ (as of v1.5.0), which may exclude legacy Laravel applications (e.g., Laravel 7).
    • Mitigation: Evaluate compatibility with your Laravel version or use a fork/patch for older PHP versions.
  • Lack of Advanced Features:
    • Risk: Missing Redis/Memcached features (e.g., cache sharding, LRU eviction, memory limits).
    • Mitigation: Accept limitations upfront; use only for simple, transient caching needs.

Key Questions

  1. Use Case Clarity:
    • Where in the stack will this replace existing caches? (e.g., tests, fallbacks, local dev)
    • Are there long-running processes (e.g., queues) where memory leaks could occur?
  2. Performance Trade-offs:
    • What’s the acceptable latency for in-memory cache operations in production?
    • Will this be used for high-frequency or high-volume caching?
  3. Testing Strategy:
    • How will this integrate with existing test suites? (e.g., replacing Cache::shouldReceive())
    • Will frozen-time testing (PSR-20 clocks) be needed for TTL assertions?
  4. Fallback Strategy:
    • How will this be configured as a secondary cache driver in config/cache.php?
    • What’s the failover priority (e.g., in-memory > Redis > APCu)?
  5. Maintenance:
    • Who will monitor memory usage in production (if used as a fallback)?
    • How will cache invalidation be handled (e.g., Cache::forget() triggers)?

Integration Approach

Stack Fit

  • Laravel Compatibility:
    • PSR-6 Driver: Register the package as a custom cache driver in config/cache.php:
      'in_memory' => [
          'driver' => 'cache',
          'store' => Beste\Cache\InMemoryCache::class,
      ],
      
    • Facade Integration: Use Cache::store('in_memory') or set CACHE_DRIVER=in_memory in .env.
    • Event Support: Works with Laravel’s cache events (e.g., Cache::store()) via PSR-6’s save()/delete() methods.
  • Testing Framework:
    • Replace mocks/stubs for Illuminate\Contracts\Cache\Store with real InMemoryCache instances.
    • Leverage PSR-20 clocks (e.g., Beste\Clock\FrozenClock) for time-based assertions:
      use Beste\Clock\FrozenClock;
      use Beste\Cache\InMemoryCache;
      
      $clock = FrozenClock::fromUTC();
      $cache = new InMemoryCache($clock);
      $cache->save($cache->getItem('key')->set('value')->expiresAfter(new DateInterval('PT5M')));
      $clock->setTo($clock->now()->add(new DateInterval('PT6M')));
      $this->assertFalse($cache->getItem('key')->isHit());
      
  • Artisan Commands:
    • Support php artisan cache:clear by manually clearing the cache in a service provider:
      public function boot()
      {
          Cache::extend('in_memory', function () {
              return new Beste\Cache\InMemoryCache();
          });
          Cache::store('in_memory')->clear(); // Clear on boot if needed
      }
      

Migration Path

  1. Testing Phase:
    • Replace external cache dependencies in tests with InMemoryCache.
    • Update test assertions to use real cache interactions (e.g., isHit(), get()).
    • Example migration:
      // Before: Mocking
      Cache::shouldReceive('get')->once()->andReturn('value');
      
      // After: Real in-memory cache
      $cache = new Beste\Cache\InMemoryCache();
      $cache->save($cache->getItem('key')->set('value'));
      $this->assertEquals('value', $cache->getItem('key')->get());
      
  2. Development Environment:
    • Add to composer.json and configure in .env:
      CACHE_DRIVER=in_memory
      
    • Update config/cache.php to include the driver (see Stack Fit above).
  3. Production Fallback:
    • Configure as a secondary driver in config/cache.php:
      'stores' => [
          'in_memory' => [
              'driver' => 'cache',
              'store' => Beste\Cache\InMemoryCache::class,
              'priority' => 2, // Lower priority than Redis
          ],
      ],
      
    • Use Laravel’s Cache::store() to route requests:
      $value = Cache::store('in_memory')->get('fallback_key', function () {
          return $this->fetchFromDatabase();
      });
      

Compatibility

  • Laravel Versions:
    • Supported: Laravel 8+ (PHP 8.1+). For Laravel 7, use v1.4.0 or earlier (PHP 8.0+).
    • Legacy: Not recommended for Laravel <7 due to PHP 8.3+ requirement (v1.5.0+).
  • Dependencies:
    • PSR-6: Fully compatible with Laravel’s Illuminate\Contracts\Cache\Store.
    • PSR-20: Optional clock integration (e.g., Beste\Clock\FrozenClock) for testing.
    • No Conflicts: Zero external dependencies beyond PHP 8.3+ and PSR-6 interfaces.
  • Key Validation:
    • Supports Laravel’s dynamic key generation (e.g., Cache::tags()) with extended PSR-6 key rules (e.g., dashes -).

Sequencing

1

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.
codraw/graphviz
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata