Weave 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

Cache Bundle Laravel Package

bash/cache-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bash/cache-bundle
    

    Ensure phpredis, igbinary, and symfony/framework-bundle (≥5.0) are installed.

  2. Enable the Bundle Add to config/bundles.php:

    Bash\CacheBundle\BashCacheBundle::class => ['all' => true],
    
  3. Basic Configuration Update config/packages/bash_cache.yaml (or create it):

    bash_cache:
        driver: 'redis'  # or 'array' for testing
        redis:
            host: '127.0.0.1'
            port: 6379
            password: null
            database: 0
    
  4. First Use Case Cache a simple value:

    use Bash\CacheBundle\Cache\CacheInterface;
    
    class MyService {
        public function __construct(private CacheInterface $cache) {}
    
        public function getCachedData() {
            $key = 'my_key';
            $value = $this->cache->get($key);
    
            if (!$value) {
                $value = 'expensive_computation_result';
                $this->cache->set($key, $value, 3600); // 1-hour TTL
            }
            return $value;
        }
    }
    

Implementation Patterns

Core Workflows

  1. Dependency Injection Inject CacheInterface (or RedisCache/ArrayCache) into services:

    public function __construct(private RedisCache $redisCache) {}
    
  2. Tag-Based Invalidation Use tags for grouped cache invalidation:

    $this->redisCache->set('user:123', $userData, 3600, ['users']);
    $this->redisCache->clearByTag('users'); // Invalidate all tagged keys
    
  3. Automatic Tagging Extend AbstractCache to auto-tag keys:

    class MyCache extends AbstractCache {
        protected function getTagsForKey(string $key): array {
            return ['my_app', explode(':', $key)[0]];
        }
    }
    
  4. Fallback Logic Combine with Symfony’s CacheInterface for hybrid caching:

    $data = $this->cache->get('key', function() {
        return $this->fallbackService->loadData();
    });
    

Integration Tips

  • Doctrine ORM: Use clearByTag() after bulk updates:
    $entityManager->flush();
    $this->redisCache->clearByTag('entities');
    
  • API Responses: Cache serialized responses:
    $response = $this->redisCache->get('api:users', function() {
        return json_encode($this->userRepository->findAll());
    });
    
  • CLI Commands: Clear cache via console:
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class ClearCacheCommand extends Command {
        protected function execute(InputInterface $input, OutputInterface $output) {
            $this->redisCache->clear();
            $output->writeln('Cache cleared!');
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Redis Connection Issues

    • Ensure phpredis is installed (pecl install redis).
    • Check php.ini for extension=redis.so.
    • Debug with:
      $this->redisCache->getRedis()->ping(); // Should return 'PONG'
      
  2. Serialization Quirks

    • igbinary must be installed for efficient Redis serialization.
    • Fallback to serialize() in config/packages/bash_cache.yaml:
      bash_cache:
          serializer: 'serialize' # or 'igbinary'
      
  3. Tagging Edge Cases

    • Avoid keys with : in untagged scenarios (tags split on :).
    • Test clearByTag() with empty tag arrays.
  4. TTL Granularity

    • Redis TTLs are in seconds (not milliseconds). Use 3600 for 1 hour.

Debugging

  • Enable Logging Add to config/packages/bash_cache.yaml:

    bash_cache:
        debug: true
    

    Logs appear in var/log/dev.log.

  • Inspect Redis Keys Use redis-cli to verify keys:

    redis-cli KEYS "*"
    redis-cli TTL "my_key"
    

Extension Points

  1. Custom Drivers Implement CacheInterface for alternative backends (e.g., Memcached):

    class MemcachedCache implements CacheInterface {
        // ...
    }
    
  2. Event Listeners Extend cache events (e.g., CacheItemMissedEvent):

    use Bash\CacheBundle\Event\CacheEvents;
    
    $dispatcher->addListener(CacheEvents::MISS, function($event) {
        if ($event->getKey() === 'critical_data') {
            $event->setValue('fallback_value');
        }
    });
    
  3. Configuration Overrides Override defaults in environment-specific configs:

    # config/packages/dev/bash_cache.yaml
    bash_cache:
        redis:
            host: 'redis-dev'
    

Performance Tips

  • Prefix Keys Avoid collisions by prefixing keys:
    $this->redisCache->set('app:user:123', $data);
    
  • Batch Operations Use mget()/mset() for multiple keys:
    $this->redisCache->mset([
        'key1' => 'value1',
        'key2' => 'value2',
    ]);
    
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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator