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

Laminas Cache Storage Adapter Session Laravel Package

laminas/laminas-cache-storage-adapter-session

Session-based cache storage adapter for Laminas Cache. Stores cached items in PHP sessions, useful for per-user caching and small transient data. Integrates with Laminas\Cache\Storage; suitable for apps already relying on session state.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laminas/laminas-cache-storage-adapter-session
    
  2. Basic Usage:

    use Laminas\Cache\Storage\Adapter\Session;
    
    $sessionAdapter = new Session();
    $sessionAdapter->setItem('key', 'value');
    $value = $sessionAdapter->getItem('key');
    
  3. Laravel Integration:

    use Laminas\Cache\Storage\Adapter\Session;
    use Psr\Container\ContainerInterface;
    
    $container->set(AdapterInterface::class, function (ContainerInterface $container) {
        return new Session();
    });
    

First Use Case

Use this adapter for short-lived, user-specific cached data (e.g., form inputs, user preferences, or temporary session-based computations). It’s ideal when:

  • Data must persist only for the current session.
  • You want to avoid external storage (e.g., Redis, file system) for lightweight caching.

Implementation Patterns

Core Workflows

  1. Session-Aware Caching:

    // Store user-specific data tied to their session
    $adapter->setItem('user_prefs', ['theme' => 'dark']);
    
    // Retrieve later in the same session
    $prefs = $adapter->getItem('user_prefs');
    
  2. Laravel Service Provider Integration:

    use Illuminate\Support\ServiceProvider;
    use Laminas\Cache\Storage\Adapter\Session;
    
    class CacheServiceProvider extends ServiceProvider {
        public function register() {
            $this->app->singleton('laminas.session.cache', function () {
                return new Session();
            });
        }
    }
    
  3. PSR-16 Cache Interface Compliance:

    // Works with PSR-16-compliant consumers (e.g., Laravel's cache facade)
    $cache = new Session();
    $cache->set('temp_key', 'temp_value', 3600); // 1-hour TTL
    

Integration Tips

  • Laravel Cache Facade: Bind the adapter to Laravel’s cache system via CacheServiceProvider:

    $this->app->bind('cache.store.session', function () {
        return new Session();
    });
    

    Then use it in config:

    'stores' => [
        'session' => [
            'driver' => 'laminas.session',
        ],
    ],
    
  • Middleware for Session Data: Use the adapter in middleware to cache user-specific responses:

    public function handle($request, Closure $next) {
        $cacheKey = 'user_dashboard_' . auth()->id();
        $data = cache()->store('session')->get($cacheKey);
    
        if (!$data) {
            $data = $next($request)->getContent();
            cache()->store('session')->put($cacheKey, $data, now()->addMinutes(10));
        }
        return response($data);
    }
    
  • Fallback to File/Redis: Combine with other adapters for hybrid caching:

    $fallback = new FileSystem();
    $sessionAdapter = new Session($fallback); // Fallback if session fails
    

Gotchas and Tips

Pitfalls

  1. Session Dependency:

    • The adapter requires a valid PHP session. Ensure session_start() is called before use.
    • Debugging: Check session_id() is set; otherwise, the adapter will fail silently.
  2. TTL Ignored:

    • Time-to-live (TTL) settings are not enforced because sessions are inherently ephemeral. Data persists only for the session lifetime.
  3. Memory Usage:

    • Session data is stored in memory. For large applications, this can bloat memory usage. Monitor with:
      ini_get('session.gc_maxlifetime'); // Check session lifetime
      
  4. Laravel Session Conflicts:

    • If using Laravel’s session driver (e.g., file, database), the adapter may overwrite or conflict with session data. Use distinct keys:
      $adapter->setItem('cache_key_prefix_', $data); // Avoid collisions
      

Debugging

  • Adapter Not Working? Verify the session is active:
    if (empty($_SESSION)) {
        session_start();
    }
    
    Check for errors with:
    try {
        $adapter->getItem('test');
    } catch (\RuntimeException $e) {
        // Handle session errors
    }
    

Extension Points

  1. Custom Session Handler: Extend the adapter to use a custom session handler:

    use Laminas\Cache\Storage\Adapter\Session;
    use Laminas\Cache\Storage\Adapter\SessionOptions;
    
    $options = new SessionOptions();
    $options->setHandler(new CustomSessionHandler());
    $adapter = new Session($options);
    
  2. PSR-16 Wrapper: Create a wrapper to add TTL support (since the adapter ignores it):

    class SessionCache implements Psr\SimpleCache\CacheInterface {
        private $adapter;
    
        public function __construct(Session $adapter) {
            $this->adapter = $adapter;
        }
    
        public function get($key, $default = null) {
            return $this->adapter->getItem($key) ?? $default;
        }
    
        public function set($key, $value, $ttl = null) {
            $this->adapter->setItem($key, $value);
            return true;
        }
        // Implement remaining PSR-16 methods...
    }
    
  3. Laravel Cache Extension: Extend Laravel’s cache system to support the adapter:

    namespace App\Extensions;
    
    use Laminas\Cache\Storage\Adapter\Session;
    use Illuminate\Cache\Repository;
    
    class SessionCache extends Repository {
        public function __construct() {
            $this->store = new Session();
        }
    }
    

    Register in config/cache.php:

    'stores' => [
        'session' => [
            'driver' => 'session',
            'class' => App\Extensions\SessionCache::class,
        ],
    ],
    

Configuration Quirks

  • Session Name: The adapter uses the default session name (PHPSESSID). Override it via ini_set('session.name', 'custom_name') if needed.

  • Garbage Collection: Session garbage collection (session.gc_probability and session.gc_divisor) affects the adapter. Adjust in php.ini or runtime:

    ini_set('session.gc_maxlifetime', 1440); // 24 minutes
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky