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

Phpfastcache Bundle Laravel Package

effiana/phpfastcache-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer (Symfony Flex auto-configures):

    composer require phpfastcache/phpfastcache-bundle
    
    • No manual AppKernel registration needed (Flex handles it).
  2. Configure Cache Driver (.env):

    # Example: Filesystem driver (default)
    CACHE_DRIVER=filesystem
    CACHE_PATH=%kernel.project_dir%/var/cache
    
    # Alternative: APCu, Redis, Memcached, etc.
    CACHE_DRIVER=apcu
    
  3. First Use Case: Cache a Controller Response Inject the PhpFastCache service into a controller:

    use PhpFastCache\PhpFastCache;
    use Symfony\Component\HttpFoundation\Response;
    
    class HomeController extends AbstractController
    {
        public function index(PhpFastCache $cache): Response
        {
            $cacheKey = 'homepage_content';
            $content = $cache->getItem($cacheKey);
    
            if (!$content->isHit()) {
                $content->set(expiresAfter(3600)); // 1 hour TTL
                $content->set('Hello, cached world!');
                $cache->save($content);
            }
    
            return new Response($content->get());
        }
    }
    
  4. Verify Installation

    • Check the Symfony Profiler’s Cache tab for PhpFastCache metrics.
    • Run php bin/console cache:clear to test cache operations.

Implementation Patterns

Core Workflows

1. Caching Data with TTL (Time-to-Live)

// Cache with 5-minute TTL
$item = $cache->getItem('user_123_data');
if (!$item->isHit()) {
    $item->set(expiresAfter(300)); // 5 minutes
    $item->set($this->fetchUserData(123));
    $cache->save($item);
}
return $item->get();

2. Cache Tags for Batch Invalidation

// Cache with tags (e.g., 'users', 'premium')
$item = $cache->getItem('user_123_profile');
$item->setTags(['users', 'premium']);
$item->set(expiresAfter(3600));
$cache->save($item);

// Invalidate all 'users' tagged items
$cache->invalidateTags(['users']);

3. Twig Caching

  • Enable Twig cache in config/packages/twig.yaml:
    twig:
        cache: true
        cache_prefix: '%kernel.cache_dir%/twig'
    
  • Use the cache tag in templates:
    {% cache app.homepage (request.uri) %}
        {{ render(controller('AppController:homepage')) }}
    {% endcache %}
    

4. Cache Profiler Integration

  • Access cache stats via Symfony Profiler:
    • Cache Hits/Misses: Shows how often cached items were reused.
    • Tag Invalidation: Logs invalidation events.
    • TTL Expirations: Tracks expired items.

Integration Tips

Dependency Injection

  • Autowire the PhpFastCache service (recommended):
    public function __construct(private PhpFastCache $cache) {}
    
  • Custom Cache Pools:
    # config/services.yaml
    services:
        App\Cache\CustomPool:
            arguments:
                - '@phpfastcache.cache.pool' # Base pool
                - 'custom_pool'             # Unique pool name
    

Event-Driven Cache Invalidation

  • Listen to cache.invalidate events (e.g., after user updates):
    use Symfony\Component\EventDispatcher\GenericEvent;
    
    public function onUserUpdate(GenericEvent $event): void
    {
        $this->cache->invalidateTags(['users']);
    }
    

Fallback Logic

  • Use get() with a fallback:
    $data = $cache->get('expensive_query', function() {
        return $this->db->query('SELECT * FROM large_table');
    });
    

Gotchas and Tips

Pitfalls

  1. Driver Compatibility

    • APCu: Requires apcu.enable_cli=1 in php.ini for CLI cache operations.
    • Redis/Memcached: Ensure the PHP extension (php-redis, php-memcached) is installed.
    • Filesystem: Permissions must allow writing to CACHE_PATH (e.g., chmod -R 775 var/cache).
  2. Tag Invalidation Quirks

    • Tags are case-sensitive. Use consistent casing (e.g., ['Users'] vs ['users']).
    • Invalidating tags does not clear the cache pool’s metadata immediately. Use invalidateAll() for a full reset.
  3. TTL Precision

    • TTL is not guaranteed to be exact (e.g., expiresAfter(1) may expire after 1.1 seconds).
    • For critical time-sensitive data, use expiresAt() with new \DateTime('+1 second').
  4. Symfony Profiler Overhead

    • Profiling adds ~5–10ms per request. Disable in production if unused:
      # config/packages/dev/profiler.yaml
      profiler: false
      
  5. Serialization Issues

    • Unserializable objects (e.g., closures, resources) cannot be cached. Use serialize()/unserialize() for custom objects:
      $item->set(serialize($unserializableObject));
      return unserialize($item->get());
      

Debugging Tips

  1. Check Cache Contents

    • Dump the cache pool’s items (dev environment only):
      $items = $cache->getPool()->getItems();
      dd($items);
      
  2. Enable Verbose Logging

    • Configure Monolog to log cache operations:
      # config/packages/monolog.yaml
      handlers:
          cache:
              type: stream
              path: "%kernel.logs_dir%/cache.log"
              channels: ["cache"]
      
    • Log cache hits/misses in a service:
      $this->logger->info('Cache miss', ['key' => $key, 'pool' => $cache->getPool()->getName()]);
      
  3. Clear Stale Cache

    • Force a full clear (use sparingly in production):
      php bin/console cache:pool:clear phpfastcache.cache.pool
      

Extension Points

  1. Custom Cache Item Class

    • Extend PhpFastCache\CacheItem to add metadata:
      class ExtendedCacheItem extends CacheItem {
          private $requestId;
      
          public function setRequestId(string $id): self {
              $this->requestId = $id;
              return $this;
          }
      }
      
    • Register the custom class in services.yaml:
      services:
          App\Cache\ExtendedCacheItem:
              tags: ['phpfastcache.cache_item']
      
  2. Dynamic Pool Configuration

    • Override pool settings per environment:
      # config/packages/prod/phpfastcache.yaml
      phpfastcache:
          pools:
              default:
                  adapter: apcu
                  prefix: 'prod_'
                  default_ttl: 86400 # 1 day
      
  3. Cache Warmer

    • Pre-load critical cache items during deployment:
      use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
      
      class CacheWarmer implements CacheWarmerInterface {
          public function warmUp($cacheDir): void {
              $cache = $this->container->get('phpfastcache.cache.pool');
              $cache->save($cache->getItem('homepage')->set('preloaded'));
          }
      }
      
    • Register in services.yaml:
      services:
          App\Cache\CacheWarmer:
              tags: [kernel.cache_warmer]
      
  4. PSR-6 Compatibility

    • Use the underlying phpfastcache library directly for PSR-6 compliance:
      use PhpFastCache\CacheManager;
      use PhpFastCache\Cache\CacheInterface;
      
      $cacheManager = new CacheManager();
      $cache = $cacheManager->getInstance('apcu');
      $item = $cache->getItem('psr6_key');
      
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
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
spatie/mailcoach-vapor