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

Opcache Laravel Package

typhoon/opcache

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Add the package via Composer:
    composer require typhoon/opcache
    
  2. Basic Usage: Initialize the cache with a directory path:
    use Typhoon\OPcache\TyphoonOPcache;
    
    $cache = new TyphoonOPcache(storage_path('framework/cache/opcache'));
    
  3. First Use Case: Cache a value for later retrieval:
    $cache->set('user.123', ['name' => 'John', 'email' => 'john@example.com']);
    $user = $cache->get('user.123'); // Returns the cached array
    

Key Files to Review

  • TyphoonOPcache.php: Core class with PSR-16 methods.
  • tests/: Example usage patterns and edge cases.

Implementation Patterns

Common Workflows

  1. Caching Expensive Operations:

    $expensiveData = $cache->get('expensive.data');
    if ($expensiveData === null) {
        $expensiveData = computeExpensiveOperation();
        $cache->set('expensive.data', $expensiveData, new DateInterval('P1D'));
    }
    
  2. Tag-Based Invalidation (Manual):

    // Prefix keys with tags (e.g., "user.123" → "users:123")
    $cache->delete('users:123'); // Invalidate all keys for user 123
    
  3. Integration with Laravel:

    • Register as a cache driver in config/cache.php:
      'drivers' => [
          'opcache' => [
              'driver' => Typhoon\OPcache\TyphoonOPcache::class,
              'path' => storage_path('framework/cache/opcache'),
              'default_ttl' => 'PT1H',
          ],
      ],
      
    • Use via the facade:
      Cache::driver('opcache')->set('key', 'value');
      
  4. Batch Operations:

    $cache->deleteMultiple(['key1', 'key2', 'key3']);
    $cache->getMultiple(['key1', 'key2']); // Returns array of cached values
    

Best Practices

  • Directory Permissions: Ensure the cache directory is writable by PHP (chmod -R 755 storage/framework/cache/opcache).
  • TTL Strategy: Use DateInterval for clarity (e.g., new DateInterval('PT2H') for 2 hours).
  • Key Naming: Use namespaces (e.g., module.feature.key) to avoid collisions.

Gotchas and Tips

Pitfalls

  1. OPcache Invalidation:

    • Changes to cached files won’t trigger OPcache invalidation automatically. Restart PHP or use opcache_reset() if needed.
    • Workaround: Append a version hash to keys (e.g., key.v1) and invalidate old versions.
  2. File Descriptor Limits:

    • Storing millions of small files may hit system limits. Monitor with:
      ulimit -n
      
    • Solution: Use a subdirectory per namespace (e.g., storage/framework/cache/opcache/users).
  3. Serialization Quirks:

    • The package serializes values to PHP files. Complex objects (e.g., closures, resources) won’t cache.
    • Tip: Cache only serializable data (arrays, strings, simple objects).
  4. Race Conditions:

    • Concurrent set() calls may overwrite each other. Use get() + set() patterns for idempotency.

Debugging

  • Verify Cache Files: Check the directory for generated .php files (e.g., storage/framework/cache/opcache/key.php).
  • Log Pruning: Add logging to prune() to track stale item removal:
    $cache->prune(); // Logs deleted keys if enabled
    
  • TTL Validation: Use cache:clear (Laravel) or manually delete files to test expiration.

Extension Points

  1. Custom Serialization: Override the serialize()/unserialize() methods in a subclass for custom data formats:

    class CustomOPcache extends TyphoonOPcache {
        protected function serialize($value) {
            return json_encode($value); // Custom logic
        }
    }
    
  2. Event Hooks: Extend the class to trigger events (e.g., CacheHit, CacheMiss) using PHP’s spl_object_id or a DI container.

  3. Fallback Cache: Combine with another PSR-16 cache (e.g., Redis) for a hybrid system:

    $opcache = new TyphoonOPcache(...);
    $redis = new RedisCache(...);
    
    $value = $opcache->get('key') ?? $redis->get('key');
    

Configuration Quirks

  • Default TTL: Must be a DateInterval object or null (not a string). Example:
    $cache = new TyphoonOPcache(..., new DateInterval('PT30M')); // 30 minutes
    
  • Directory Creation: The package won’t create the directory automatically. Ensure it exists or handle DirectoryNotFoundException.

Performance Tips

  • OPcache Warmup: Pre-load critical cache files during deployment to avoid cold starts.
  • File Permissions: Use 750 (not 777) for security if the directory is shared.
  • Avoid Frequent Pruning: Schedule prune() via Laravel’s scheduler (e.g., @daily) instead of running it on every request.
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