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

Session Handler Laravel Package

cache/session-handler

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require cache/session-handler
    
  2. Configure Laravel’s session driver in config/session.php:
    'driver' => 'custom',
    'handler' => \Cache\SessionHandler::class,
    
  3. Register the handler in AppServiceProvider:
    public function register()
    {
        $this->app->singleton(\SessionHandlerInterface::class, function ($app) {
            $pool = $app->make(\Psr\Cache\CacheItemPoolInterface::class);
            return new \Cache\SessionHandler($pool, [
                'ttl' => $app['config']['session.lifetime'],
                'prefix' => 'laravel_session_',
            ]);
        });
    }
    

First Use Case

Replace Laravel’s default file/database session storage with a PSR-6 cache pool (e.g., Redis, Memcached, or even array for testing). Example with Redis:

// config/cache.php
'default' => env('CACHE_DRIVER', 'redis'),
'stores' => [
    'redis' => [
        'driver' => 'redis',
        'connection' => 'cache',
    ],
],

Implementation Patterns

Workflows

  1. Cache Pool Integration

    • Use Laravel’s existing PSR-6 cache configuration (e.g., Cache::store('redis')) to inject the pool into the session handler.
    • Example:
      $pool = Cache::store('redis')->getCacheItemPool();
      $handler = new \Cache\SessionHandler($pool, ['ttl' => 3600]);
      
  2. Session Lifetime Management

    • Leverage Laravel’s session.lifetime config to auto-set TTL:
      $handler = new \Cache\SessionHandler($pool, [
          'ttl' => config('session.lifetime'),
          'prefix' => config('session.prefix').'_',
      ]);
      
  3. Fallback for Missing Cache Drivers

    • Use array pool for local development/testing:
      $pool = new \Symfony\Component\Cache\Adapter\ArrayAdapter();
      
  4. Middleware Integration

    • Extend Laravel’s StartSession middleware to use the custom handler:
      protected function getSessionHandler()
      {
          return app(\SessionHandlerInterface::class);
      }
      

Advanced Patterns

  • Tag-Based Invalidation Use PSR-6 tags to invalidate sessions globally (e.g., on user logout):
    Cache::tags(['session_user_123'])->clear();
    
  • Custom Serialization Override serialize()/unserialize() in a decorator class for complex session data:
    class CustomSessionHandler extends \Cache\SessionHandler {
        public function read($sessionId): string {
            $data = parent::read($sessionId);
            return json_decode($data, true); // Custom logic
        }
    }
    

Gotchas and Tips

Pitfalls

  1. No Locking

    • Concurrency issues: The handler lacks file-based locking, so concurrent writes will overwrite sessions. Mitigate with:
      • External locking (e.g., Redis SETNX).
      • Short-lived sessions (e.g., ttl=300).
    • Workaround: Use a mutex library like spatie/laravel-redis-mutex.
  2. TTL Misconfiguration

    • Sessions expire immediately if ttl is 0 or omitted. Always set a value:
      'ttl' => config('session.lifetime', 120), // Default to 2 minutes
      
  3. Prefix Collisions

    • Default prefix ('laravel_session_') may clash with other PSR-6 caches. Use unique prefixes:
      'prefix' => 'app_'.config('app.name').'_session_',
      
  4. Large Session Data

    • PSR-6 caches may reject oversized items. Validate session size in middleware:
      if (strlen(session('data')) > 100 * 1024) { // 100KB limit
          throw new \RuntimeException('Session too large');
      }
      

Debugging Tips

  • Check Cache Pool Verify items exist in the cache pool:
    $item = $pool->getItem("laravel_session_{$sessionId}");
    var_dump($item->isHit());
    
  • Log Serialized Data Debug corrupted sessions by logging raw data:
    $handler->read($sessionId); // Log output for inspection
    
  • Test with array Pool Use ArrayAdapter for local debugging to avoid cache server issues.

Extension Points

  1. Custom Handler Decorator Extend the handler to add features (e.g., encryption):

    class EncryptedSessionHandler extends \Cache\SessionHandler {
        public function write($sessionId, $data): bool {
            $encrypted = openssl_encrypt($data, 'AES-256-CBC', config('app.key'));
            return parent::write($sessionId, $encrypted);
        }
    }
    
  2. Event Listeners Hook into session events (e.g., session_start) to log or transform data:

    event(new SessionStarting);
    
  3. Cache Pool Events Subscribe to PSR-6 cache events (e.g., CacheItemPoolInterface events) for real-time invalidation:

    $pool->getItem('key')->isHit(); // Trigger custom logic
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle