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 Bundle Laravel Package

tedivm/stash-bundle

Symfony bundle integrating the Stash caching library. Provides cache pool services, Web Profiler toolbar info, and Doctrine Common Cache integration. Supports multiple cache backends with simple YAML configuration and easy access to default or custom pools.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require tedivm/stash-bundle

Add to config/bundles.php (Symfony 4+):

return [
    // ...
    Tedivm\StashBundle\TedivmStashBundle::class => ['all' => true],
];
  1. Basic Configuration (config/packages/stash.yaml):

    stash:
        drivers: [FileSystem]
        FileSystem: ~
    
  2. First Use Case: Inject the cache pool into a service/controller:

    use Stash\Pool;
    
    class MyService
    {
        public function __construct(private Pool $cachePool) {}
    
        public function getCachedData(string $key): mixed
        {
            $item = $this->cachePool->getItem($key);
            if (!$item->isMiss()) {
                return $item->get();
            }
    
            $data = $this->fetchFreshData($key);
            $item->set($data, 3600); // Cache for 1 hour
            return $data;
        }
    }
    

Key First Steps

  • Dependency Injection: Use Pool interface for type-hinting.
  • Web Profiler: Cache stats appear automatically in dev/test environments.
  • Doctrine Integration: Enable via registerDoctrineAdapter: true for ORM caching.

Implementation Patterns

Common Workflows

1. Multi-Layer Caching

Leverage composite drivers for fallback logic (e.g., APC → Filesystem):

stash:
    drivers: [Apc, FileSystem]
    Apc: ~
    FileSystem:
        path: "%kernel.cache_dir%/stash_fallback"

2. Environment-Specific Configs

Use %kernel.environment% for dynamic backends:

stash:
    drivers: [%env(STASH_DRIVER)%]
    Redis:
        servers: ["%env(REDIS_URL)%"]

3. Tagged Caching

Use tags for bulk invalidation (Stash v0.12+):

$item = $pool->getItem('user:123', ['users', 'premium']);
$item->set($userData, 3600);
$pool->invalidateTags(['users']); // Clears all tagged items

4. Doctrine ORM Caching

Configure in config/packages/doctrine.yaml:

doctrine:
    orm:
        metadata_cache_driver: stash.adapter.doctrine.default_cache
        query_cache_driver: stash.adapter.doctrine.default_cache

5. Session Storage

Enable session adapter:

stash:
    registerSessionHandler: true
framework:
    session:
        handler_id: stash.adapter.session.default_cache

Integration Tips

  • PSR-6 Compliance: Use Stash\Pool as a drop-in replacement for PSR-6 caches where supported.
  • TTL Strategies:
    • Absolute: new \DateTime('+1 hour')
    • Relative: 3600 (seconds)
    • Dynamic: Fetch TTL from data (e.g., set($data, $data['expires_at'])).
  • Key Design:
    • Prefix keys with service names (e.g., user:123 vs. product:456).
    • Use namespaces for multi-cache setups (e.g., cache1:key vs. cache2:key).

Gotchas and Tips

Pitfalls

  1. Key Collisions:

    • Multi-cache setups require explicit namespacing (e.g., cache1:key vs. cache2:key).
    • Fix: Use stash.caches.{name}.namespace in config.
  2. TTL Precision:

    • Floating-point TTLs (e.g., 3600.5) may behave unexpectedly across drivers.
    • Fix: Use integer seconds or DateTime objects.
  3. Doctrine Adapter Quirks:

    • Only works with Doctrine\Common\Cache\CacheProvider interfaces.
    • Fix: Ensure your Doctrine config targets the adapter service ID (e.g., stash.adapter.doctrine.default_cache).
  4. Session Adapter Limitations:

    • Not thread-safe for concurrent requests.
    • Fix: Use only in single-process environments or with external session storage.
  5. Tracking Overhead:

    • Enabling tracking_values: true logs sensitive data.
    • Fix: Disable in production (stash.tracking: false).

Debugging

  • Web Profiler: Check the "Stash" tab for cache hits/misses and execution times.
  • Logs: Enable PSR-3 logging to trace cache operations:
    stash:
        logger: monolog.logger.cache
    
  • TTL Issues: Use stash.tracking: true to verify TTL application.

Configuration Quirks

  1. Driver Order Matters:

    • Composite drivers query in declaration order (first match wins).
    • Example: [Apc, FileSystem] checks APC first, falls back to filesystem.
  2. Filesystem Permissions:

    • Default dirPermissions: 0770 may fail on shared hosting.
    • Fix: Adjust or use umask in your deployment script.
  3. Redis Connection:

    • Requires php-redis extension and proper server configuration.
    • Fix: Validate with php -m | grep redis and test connection manually.
  4. Memcached Options:

    • remove_failed_servers must be enabled in php.ini for the option to work.
    • Fix: Add memcache.remove_failed_servers = 1 to php.ini.

Extension Points

  1. Custom Drivers:

    • Extend Stash\Driver\DriverInterface and register via stash.drivers service tag.
    • Example:
      services:
          App\Cache\MyDriver:
              tags: ['stash.driver']
      
  2. Event Listeners:

    • Subscribe to stash.cache_item_miss or stash.cache_item_hit events for analytics.
    • Example:
      use Stash\Event\CacheEvent;
      
      $dispatcher->addListener('stash.cache_item_miss', function (CacheEvent $event) {
          // Log miss with metadata
      });
      
  3. Encoder Overrides:

    • Replace the default Native encoder with Json or Php:
      FileSystem:
          encoder: Json
      
  4. Cache Warmers:

    • Implement Stash\CacheWarmerInterface for pre-loading critical data.
    • Example:
      class ProductCacheWarmer implements CacheWarmerInterface
      {
          public function warmUp(Pool $pool): array
          {
              $keys = ['product:1', 'product:2'];
              foreach ($keys as $key) {
                  $pool->getItem($key)->set($this->fetchProduct($key), 3600);
              }
              return $keys;
          }
      }
      
      Register as a service tagged with kernel.cache_warmer.

Performance Tips

  • In-Memory Cache: Disable inMemory: true for CLI scripts to avoid memory leaks.
  • Batch Operations: Use Pool::getItems() for multiple keys to reduce overhead:
    $items = $pool->getItems(['key1', 'key2']);
    foreach ($items as $item) {
        if ($item->isMiss()) {
            $item->set($this->fetchData($item->getKey()));
        }
    }
    
  • Compression: Enable for large values (e.g., Redis with compression: true).

Migration Notes

  • Symfony 4+: Replace AppKernel.php with config/bundles.php.
  • Stash v0.12+: Use getItem($key, $tags) instead of getItem($key) for tagged caching.
  • Doctrine 2.8+: Ensure Doctrine\Common\Cache\CacheProvider compatibility.

---
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor