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

Cache Laravel Package

gregwar/cache

gregwar/cache is a lightweight PHP caching library with a simple API for caching values and function results. Supports multiple backends (filesystem, APC/APCu, memcache), TTL expiration, cache namespaces/prefixes, and easy integration into existing apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require gregwar/cache
    

    No additional configuration is needed—just autoload the package.

  2. Basic Usage

    use Gregwar\Cache\Cache;
    
    $cache = new Cache('/path/to/cache/directory');
    $cache->set('key', 'value', 3600); // Cache for 1 hour
    $value = $cache->get('key');
    
  3. First Use Case Cache database query results to reduce load:

    $users = $cache->remember('expensive_query', 60, function () {
        return User::all()->toArray();
    });
    

Implementation Patterns

Common Workflows

  1. Cache Warming Preload critical data during low-traffic periods:

    $cache->set('featured_products', Product::featured()->get(), 300);
    
  2. Conditional Caching Use remember() for dynamic data with fallback logic:

    $data = $cache->remember('user_'.$userId, 300, function () use ($userId) {
        return User::find($userId)->load('posts');
    });
    
  3. Cache Invalidation Clear stale data on updates:

    // After updating a user
    $cache->forget('user_'.$userId);
    $cache->forget('user_'.$userId.'_posts');
    
  4. Tag-Based Invalidation Group related cache keys (requires custom implementation):

    $cache->set('tag:products:123', $product, 3600);
    // Later: Clear all 'tag:products:*' keys
    
  5. Integration with Laravel Bind the package to Laravel’s cache manager:

    Cache::extend('gregwar', function ($app) {
        return new Gregwar\Cache\Cache(storage_path('framework/cache/gregwar'));
    });
    

    Then use Cache::driver('gregwar')->get('key').


Gotchas and Tips

Pitfalls

  1. Directory Permissions Ensure the cache directory is writable by the web server:

    chmod -R 775 /path/to/cache
    

    Symptom: Silent failures or PermissionDeniedException.

  2. Key Collisions Avoid using special characters (e.g., :, /) in keys unless URL-encoded. Fix: Sanitize keys:

    $safeKey = str_replace(['/', ':'], '_', $userId);
    
  3. Memory vs. Disk Large cached data (e.g., serialized objects) may bloat storage. Tip: Use serialize()/unserialize() for complex objects:

    $cache->set('user_data', serialize($user));
    $user = unserialize($cache->get('user_data'));
    
  4. TTL Granularity Seconds are the smallest unit. For sub-second precision, use 0 (no expiry) and manually invalidate.

  5. Race Conditions remember() is not atomic. For critical sections, use locks:

    $cache->lock('update_key', 5, function () {
        // Critical update logic
    });
    

Debugging

  • Check Cache Files Inspect /path/to/cache/ for corrupted or unexpected files.
  • Log Misses/Hits Extend the class to log cache behavior:
    $cache = new Cache($dir, [
        'logger' => new \Monolog\Logger('cache', [$handler]),
    ]);
    

Extension Points

  1. Custom Storage Override Cache::getStorage() to use S3, Redis, etc.:

    class CustomCache extends Cache {
        protected function getStorage() {
            return new \League\Flysystem\Filesystem(...);
        }
    }
    
  2. Event Hooks Trigger events on set/get/forget by extending the class and overriding methods.

  3. Compression Enable GZIP for large cache files:

    $cache->set('large_data', gzcompress($data), 3600);
    $data = gzuncompress($cache->get('large_data'));
    
  4. Fallback Cache Implement a multi-layer cache (e.g., Redis + Filesystem):

    $fallback = new Cache($dir);
    $primary = Cache::store('redis');
    return $primary->get('key') ?? $fallback->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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver