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

Stash Package Laravel Package

zingle-com/stash-package

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require zingle-com/stash-package
    

    Register the service provider in config/app.php after Laravel core providers but before custom providers:

    ZingleCom\Stash\StashServiceProvider::class,
    

    Publish config/assets:

    php artisan vendor:publish --provider="ZingleCom\Stash\StashServiceProvider"
    
  2. First Use Case: Store/retrieve data via stash facade:

    use ZingleCom\Stash\Facades\Stash;
    
    // Store data (expires in 1 hour)
    Stash::put('user.cache', $user, 3600);
    
    // Retrieve data
    $cachedUser = Stash::get('user.cache');
    
    // Check existence
    if (Stash::has('user.cache')) { ... }
    
  3. Key Files:

    • config/stash.php: Driver/configuration (e.g., driver: 'file', path: storage/framework/cache).
    • app/Stash.php: Facade alias (auto-generated after publishing).

Implementation Patterns

Core Workflows

  1. Driver-Based Storage:

    • Supports file, database, and redis drivers (configured in config/stash.php).
    • Example: Switch to Redis for high-performance caching:
      'driver' => env('STASH_DRIVER', 'file'),
      'redis' => [
          'connection' => 'cache',
      ],
      
  2. Contextual Storage:

    • Use namespaces to organize keys (e.g., user.profile.* vs. api.rate_limits.*):
      Stash::put('user.profile.settings', $settings, 86400); // 24h TTL
      
  3. TTL Management:

    • Set Time-To-Live (TTL) in seconds (e.g., 3600 = 1 hour). Omit to persist indefinitely.
    • Example: Cache API responses:
      $response = Stash::remember('api.github.user', 7200, function () {
          return Http::get('https://api.github.com/user')->json();
      });
      
  4. Integration with Laravel Features:

    • Middleware: Cache route responses:
      public function handle($request, Closure $next)
      {
          return Stash::remember('route.home', 300, function () use ($request) {
              return $next($request);
          });
      }
      
    • Events: Store event payloads temporarily:
      event(new OrderPlaced($order));
      Stash::put('order.processing.' . $order->id, $order, 300);
      
  5. Bulk Operations:

    • Use Stash::flush() to clear all cached items (e.g., after config changes).
    • Delete specific keys:
      Stash::forget('user.cache');
      

Advanced Patterns

  1. Custom Drivers:

    • Extend ZingleCom\Stash\Contracts\Driver to create a new storage backend (e.g., Memcached).
    • Bind the driver in the service provider:
      $this->app->bind('stash.driver', function ($app) {
          return new CustomDriver();
      });
      
  2. Tag-Based Invalidation:

    • Tag keys for grouped invalidation (e.g., user.* tags):
      Stash::put('user.123', $user, 3600, ['users']);
      Stash::flushByTags(['users']); // Clears all tagged keys
      
  3. Fallback Logic:

    • Combine with Laravel’s Cache facade for hybrid storage:
      $data = Stash::get('fallback.example') ?? Cache::get('fallback.example');
      

Gotchas and Tips

Pitfalls

  1. Driver Mismatches:

    • Ensure the configured driver (config/stash.php) matches your environment (e.g., redis requires Redis server).
    • Debug Tip: Check stash.log (if enabled) for driver initialization errors.
  2. TTL Precision:

    • TTL is not guaranteed to be exact (especially for file driver). Use it for approximate expiration.
  3. Key Collisions:

    • Avoid using reserved prefixes (e.g., laravel.*). Stick to a consistent namespace (e.g., app.*).
  4. File Driver Permissions:

    • Ensure the storage/framework/cache directory is writable:
      chmod -R 775 storage/framework/cache
      
  5. Memory Leaks:

    • Unbounded Stash::put() calls (without TTL) can bloat storage. Audit keys periodically:
      $keys = Stash::keys('app.*'); // List all keys with prefix
      

Debugging Tips

  1. Enable Logging: Add to config/stash.php:

    'log' => [
        'enabled' => true,
        'channel' => 'single',
    ],
    

    Check logs for driver operations:

    log:stash.*
    
  2. Inspect Storage:

    • File Driver: Browse storage/framework/cache.
    • Database Driver: Query the stash table:
      SELECT * FROM stash WHERE key LIKE 'user.%';
      
  3. Clear Stale Data: Run the stash:clear artisan command to wipe all cached items:

    php artisan stash:clear
    

Extension Points

  1. Custom Events:

    • Listen for StashStored, StashRetrieved, or StashDeleted events to log/audit operations:
      Event::listen(StashEvents::STASH_STORED, function ($event) {
          Log::info("Stored: {$event->key}", $event->data);
      });
      
  2. Macros:

    • Extend the Stash facade for project-specific methods:
      Stash::macro('getUser', function ($id) {
          return $this->get("user.{$id}");
      });
      
      Usage:
      $user = Stash::getUser(123);
      
  3. Testing:

    • Mock the Stash facade in tests:
      $this->mock(ZingleCom\Stash\Facades\Stash::class)->shouldReceive('get')
          ->with('test.key')->andReturn($mockData);
      
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php