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

Zend Cache Laravel Package

zf1/zend-cache

Zend Framework 1 cache component extracted as a standalone package. Provides caching frontends/backends for storing data, pages, and objects with adapters like file, memory, and database, plus flexible cache lifetime and tagging support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer (if available in a modern fork or via legacy support):

    composer require zf1/zend-cache
    

    (Note: Since this is a legacy Zend Framework 1 package, ensure compatibility with your Laravel environment via a custom bridge or container integration.)

  2. Basic Configuration Define a cache backend in config/cache.php (or a custom config file):

    'zend_cache' => [
        'backend' => 'File', // Options: File, Memcache, Apc, etc.
        'options' => [
            'cache_dir' => storage_path('framework/cache/zend'),
        ],
    ],
    
  3. First Use Case: Caching a Query

    use Zend_Cache;
    
    $cache = Zend_Cache::factory(
        'Core', // Cache frontend
        'File', // Backend (from config)
        [
            'lifetime' => 3600, // 1 hour
            'automatic_serialization' => true,
        ],
        [
            'cache_dir' => config('cache.zend_cache.options.cache_dir'),
        ]
    );
    
    $key = 'user_posts_123';
    $posts = $cache->getItem($key);
    
    if (!$posts) {
        $posts = User::with('posts')->find(123)->posts;
        $cache->setItem($key, $posts);
    }
    

Implementation Patterns

Common Workflows

  1. Cache-aside Pattern (Lazy Loading)

    $cache = Zend_Cache::factory('Core', 'File', ['lifetime' => 86400]);
    $data = $cache->getItem('expensive_computation');
    
    if (!$data) {
        $data = computeExpensiveData();
        $cache->setItem('expensive_computation', $data);
    }
    
  2. Write-through Pattern (Cache on Save)

    // In a User model observer or event listener
    $cache = Zend_Cache::factory('Core', 'File');
    $cache->removeItem('user_posts_' . $user->id); // Invalidate related cache
    
  3. Tag-based Invalidation

    $cache = Zend_Cache::factory('Tag', 'File', [
        'tags' => ['user_posts'],
        'lifetime' => 3600,
    ]);
    $cache->save($posts, 'user_posts_123', ['user_posts']);
    

Integration Tips

  • Laravel Service Provider Bind the cache factory to Laravel’s container:

    public function register()
    {
        $this->app->singleton('zend.cache', function ($app) {
            return Zend_Cache::factory(
                'Core',
                config('cache.zend_cache.backend'),
                config('cache.zend_cache.options.frontend'),
                config('cache.zend_cache.options.backend')
            );
        });
    }
    
  • Middleware for API Caching

    public function handle($request, Closure $next)
    {
        $cache = app('zend.cache');
        $key = 'api_response_' . $request->getPath();
        $response = $cache->getItem($key);
    
        if (!$response) {
            $response = $next($request);
            $cache->setItem($key, $response->getContent());
        }
    
        return $response;
    }
    
  • Queue Job Caching Cache results of long-running jobs:

    public function handle()
    {
        $cache = app('zend.cache');
        $result = $cache->getItem('job_result_' . $this->job->id);
    
        if (!$result) {
            $result = $this->processJob();
            $cache->setItem('job_result_' . $this->job->id, $result, 300); // 5 mins
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Legacy Compatibility

    • Zend Cache 1.x is not natively Laravel-compatible. Use a bridge like zendframework/zend-cache-bridge or wrap it in a Laravel service.
    • PHP 7+ Issues: Some older Zend Cache versions may throw E_STRICT or TypeError. Use a polyfill or fork.
  2. File Backend Permissions Ensure the cache_dir is writable:

    mkdir -p storage/framework/cache/zend
    chmod -R 775 storage/framework/cache/zend
    
  3. Memory Leaks

    • Avoid caching large objects (e.g., Eloquent collections with lazy relationships). Serialize manually if needed:
      $cache->setItem('key', serialize($data));
      $data = unserialize($cache->getItem('key'));
      
  4. Tagging Limitations

    • The Tag frontend in Zend Cache 1.x is basic. For advanced tagging, consider Laravel’s built-in cache tags or a package like spatie/laravel-cache-tags.
  5. No Automatic Tag Invalidation Manually invalidate tags when data changes:

    $cache = Zend_Cache::factory('Tag', 'File');
    $cache->removeItemByTags(['user_posts']); // Invalidate all tagged items
    

Debugging Tips

  • Check Cache Hits/Misses Enable logging in the frontend options:

    Zend_Cache::factory('Core', 'File', [
        'logging' => true,
        'log' => storage_path('logs/zend_cache.log'),
    ]);
    
  • Clear Cache Programmatically

    $cache = Zend_Cache::factory('Core', 'File');
    $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
    
  • Test with Short Lifetimes Use lifetime => 10 during development to avoid stale data.

Extension Points

  1. Custom Backends Implement Zend_Cache_Backend interface for databases (e.g., Redis, DynamoDB):

    class LaravelRedisBackend implements Zend_Cache_BackendInterface {
        public function save($data, $id, $ttl, $tags = null) {
            Redis::connection()->set($id, $data, 'EX', $ttl);
        }
        // Implement other required methods...
    }
    
  2. Hybrid Caching Combine with Laravel’s cache:

    $zendCache = app('zend.cache');
    $laravelCache = Cache::store('redis');
    
    if (!$zendCache->getItem('key')) {
        $laravelCache->put('key', $data, 3600);
    }
    
  3. Event Listeners Trigger cache invalidation on model events (e.g., saved, deleted):

    User::saved(function ($user) {
        app('zend.cache')->removeItem('user_' . $user->id);
    });
    
  4. Fallback to Laravel Cache Wrap Zend Cache in a fallback mechanism:

    $cache = app('zend.cache');
    $data = $cache->getItem('key') ?: Cache::get('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
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