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

Lightweight PSR-6 in-memory cache for PHP. Ideal as a default cache implementation and for fast, dependency-free tests. Supports expirations and can use a PSR-20 clock (e.g. frozen clock) for deterministic time-based behavior.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • PSR-6 Compliance: Perfectly aligns with Laravel’s caching abstraction (via Illuminate\Contracts\Cache\Store), enabling seamless integration with existing cache logic. The package’s adherence to PSR-6 ensures compatibility with Laravel’s Cache facade, adapters, and third-party libraries (e.g., spatie/laravel-cache).
  • Use Case Alignment:
    • Testing: Eliminates flaky external dependencies (Redis/Memcached) in unit/integration tests, providing deterministic, isolated cache behavior.
    • Fallback Mechanism: Acts as a lightweight, dependency-free fallback for production when primary caches (e.g., Redis) are unavailable. Ideal for graceful degradation in failover scenarios.
    • Development/Staging: Reduces overhead in non-production environments where persistence isn’t critical (e.g., local dev, CI/CD pipelines).
  • Laravel-Specific Synergy:
    • Works natively with Laravel’s Cache::remember(), Cache::put(), and Cache::get() methods when configured as a PSR-6 driver.
    • Supports Laravel’s event system (e.g., Cache::store() events) via PSR-6’s save()/delete() methods.
    • Compatible with Laravel’s cache:clear artisan command (if manually cleared).

Integration Feasibility

  • Low-Coupling Design: Zero configuration required beyond instantiation. Can be dropped into any Laravel application without modifying business logic.
  • PSR-20 Clock Integration: Enables advanced testing scenarios (e.g., frozen time) via Beste\Clock\FrozenClock, aligning with Laravel’s time package and travel() helper.
  • Thread/Process Safety:
    • Not Thread-Safe: Unsafe for multi-threaded environments (e.g., Swoole, ReactPHP). Must be scoped to a single request or process.
    • Process-Safe: Safe within Laravel’s request lifecycle (e.g., HTTP requests, CLI commands) 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 needed for edge cases.

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 periodic cleanup (e.g., Cache::forget() in a scheduled job).
      • Avoid use in persistent processes (e.g., use Redis for queues/workers).
  • Data Persistence:
    • Risk: Cache is wiped on process restart (e.g., php artisan queue:work restart, container redeploy).
    • Mitigation: Reserve for non-critical, ephemeral data. Use Redis for persistent caching.
  • Concurrency Issues:
    • Risk: Race conditions in multi-process environments (e.g., Laravel Horizon workers).
    • Mitigation: Restrict usage to single-process contexts (e.g., HTTP requests) or add external synchronization (e.g., Redis mutexes).
  • Performance Bottlenecks:
    • Risk: Slower than Redis/Memcached for high-throughput scenarios due to lack of persistence or distributed caching.
    • Mitigation: Benchmark and reserve for low-volume, non-critical caching.

Key Questions

  1. Environmental Scope:
    • Will this replace Redis/Memcached in production? (Not recommended; use only for fallbacks or non-critical data.)
    • Which environments will use this? (Tests, local dev, staging? Avoid long-running production processes.)
  2. Data Criticality:
    • Is the cached data recoverable if lost? (If not, avoid in-memory storage.)
    • Are there sensitive or large payloads? (Serialization limits may apply.)
  3. Process Lifecycle:
    • How long do processes run? (Long-lived processes risk memory leaks.)
    • Are there multi-process workers? (Concurrency risks exist.)
  4. Fallback Strategy:
    • How will the system handle cache misses? (Will it degrade to database or fail silently?)
    • Is there a monitoring alert for cache evictions? (Critical for production fallbacks.)
  5. Testing Strategy:
    • Will this reduce test flakiness? (Yes, but ensure tests don’t leak between runs.)
    • How will frozen time (PSR-20) be used? (For time-sensitive cache tests.)
  6. Maintenance Overhead:
    • Who will manage TTLs/cleanup? (Automated or manual?)
    • How will memory usage be monitored? (e.g., memory_get_usage() checks.)

Integration Approach

Stack Fit

  • Laravel Integration:
    • Cache Facade: Register as a PSR-6 driver in config/cache.php:
      'drivers' => [
          'in_memory' => [
              'driver' => 'cache',
              'store' => Beste\Cache\InMemoryCache::class,
          ],
      ],
      
    • PSR-6 Adapter: Use League\PSR6\Cache\CacheItemPool to bridge Laravel’s Cache facade with the package.
    • Testing: Replace Cache::shouldReceive() stubs with direct Beste\Cache\InMemoryCache assertions.
  • Non-Laravel PHP:
    • Standalone PSR-6 implementation for frameworks like Symfony, Laminas, or custom apps.
    • Works with any PSR-6-aware library (e.g., Doctrine, API Platform).
  • Tooling:
    • Laravel Mix/Tailwind: Cache template fragments or build artifacts in dev.
    • Laravel Echo/Pusher: Local event caching for testing WebSocket logic.

Migration Path

  1. Phase 1: Testing (High Priority)
    • Replace external cache dependencies in tests with Beste\Cache\InMemoryCache.
    • Example:
      $cache = new Beste\Cache\InMemoryCache();
      $cache->save($cache->getItem('test')->set('value'));
      $this->assertTrue($cache->getItem('test')->isHit());
      
    • Tools: Use Beste\Clock\FrozenClock for time-sensitive tests (e.g., TTL validation).
  2. Phase 2: Development (Medium Priority)
    • Configure as a local cache driver in .env:
      CACHE_DRIVER=in_memory
      
    • Use for non-critical caching (e.g., Cache::remember() for transient data like form inputs).
    • Example:
      $userInput = Cache::remember('form.inputs', now()->addMinutes(5), function () {
          return request()->input();
      });
      
  3. Phase 3: Production Fallback (Low Priority, Cautious)
    • Use Case: Non-persistent, read-heavy data (e.g., analytics dashboards with short TTLs).
    • Implementation:
      • Conditional driver selection:
        $driver = config('cache.default') === 'in_memory'
            ? new Beste\Cache\InMemoryCache()
            : Cache::store();
        
      • Monitoring: Log cache misses and memory usage (e.g., Cache::stats() if extended).

Compatibility

  • Laravel Versions:
    • Supported: Laravel 8+ (native PSR-6 support). For Laravel <8, use a PSR-6 adapter like spatie/laravel-cache.
    • PHP Versions: PHP 8.0+ (per package). Laravel 9+ requires PHP 8.1+.
  • Dependencies:
    • Zero External Dependencies: Pure PHP, reducing conflict risk.
    • Optional: beste/clock for PSR-20 testing (not required for basic usage).
  • Laravel Features:
    • Cache Tags: Not supported (in-memory caches lack tagging infrastructure).
    • Cache Events: Works via PSR-6’s save()/delete() events (e.g., Cache::store()->save()).

Sequencing

  1. Add to composer.json:
    composer require beste/in-memory-cache
    
  2. Register Driver (Laravel):
    • Extend Illuminate\Cache\CacheServiceProvider or use a package like spatie/laravel-cache for dynamic drivers.
    • Example Service Provider:
      public function register()
      {
          $this->app->singleton('cache.in_memory', function () {
              return new Beste\Cache\InMemoryCache();
          });
      }
      
  3. Environment-Specific Config:
    • Use config/cache.php to route in_memory driver to the package.
    • Example:
      'in_memory' => [
          'driver' => 'cache',
          'store' => Beste\Cache\InMemoryCache::class,
      ],
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope