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

Persist Laravel Package

nnjeim/persist

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require nnjeim/persist
    

    No additional configuration is required—just publish the facade or use dependency injection.

  2. First Use Case Cache an API response for 5 minutes:

    use Nnjeim\Persist\Facades\Persist;
    
    $data = Persist::setCacheTag('api_data')->setCacheKey('users')->rememberCache(5 * 60, $apiResponse);
    
  3. Key Files to Review

    • vendor/nnjeim/persist/src/Persist.php (Facade methods)
    • vendor/nnjeim/persist/src/PersistHelper.php (Core logic)

Implementation Patterns

Common Workflows

1. Caching API Responses

// Cache for 1 hour (TTL: 3600)
$data = Persist::setCacheTag('api')->setCacheKey('products')->rememberCache(3600, $apiData);

// Check if cached data exists
if (Persist::setCacheTag('api')->setCacheKey('products')->hasCacheKey()) {
    $cachedData = Persist::getCacheKey();
}

2. Cache Tags for Grouped Invalidation

// Set a tag (e.g., for invalidating all 'countries' cache)
Persist::setCacheTag('countries')->setCacheKey('index')->rememberCacheForever($data);

// Invalidate all keys with the 'countries' tag
Cache::tags('countries')->flush();

3. Dependency Injection (Recommended)

use Nnjeim\Persist\PersistHelper;

class CountryService {
    public function __construct(private PersistHelper $persist) {}

    public function fetchCountries() {
        if ($this->persist->setCacheTag('countries')->setCacheKey('index')->hasCacheKey()) {
            return $this->persist->getCacheKey();
        }
        // Fetch and cache logic...
    }
}

4. Chaining Methods

// Fluent interface for readability
$response = Persist::setCacheTag('users')
    ->setCacheKey('active')
    ->rememberCache(300, $users)
    ->getCacheKey();

5. Integration with Other Helpers

use Nnjeim\Fetch\Facades\Fetch;
use Nnjeim\Respond\Facades\Respond;

$response = Fetch::get('https://api.example.com/data');
if ($response->success) {
    Persist::setCacheTag('api')->setCacheKey('data')->rememberCache(60, $response->data);
    return Respond::toJson()->setData(Persist::getCacheKey())->withSuccess();
}

Gotchas and Tips

Pitfalls

  1. Cache Tag Mismatch

    • Forgetting to set a cacheTag before calling hasCacheKey() or getCacheKey() will silently fail or return stale data.
    • Fix: Always chain setCacheTag() before other methods.
  2. TTL Misinterpretation

    • rememberCacheForever() does not mean "indefinite"—it uses Laravel’s default cache TTL (often 0, which may not persist).
    • Fix: Use rememberCache($seconds) with a large value (e.g., 31536000 for 1 year) or configure Redis’s ttl explicitly.
  3. No Automatic Tag Invalidation

    • The package does not auto-flush tags on updates. You must manually call:
      Cache::tags('countries')->flush();
      
    • Fix: Wrap cache updates in a service layer to centralize invalidation logic.
  4. Facade vs. Helper Confusion

    • The facade (Persist::...) and helper ($persist->...) are identical in functionality. Prefer dependency injection for testability.

Debugging Tips

  1. Check Redis Directly

    redis-cli keys "*"  # List all keys (use with caution in production)
    redis-cli get "laravel:tags:countries:index"
    
  2. Log Cache Operations Add a debug method to the helper:

    // In PersistHelper.php
    public function debug(): string {
        return "Tag: {$this->cacheTag}, Key: {$this->cacheKey}";
    }
    
  3. Handle Cache Misses Gracefully

    $data = Persist::setCacheTag('api')->setCacheKey('data')->getCacheKey();
    if (is_null($data)) {
        $data = $this->fetchFreshData();
        Persist::rememberCache(3600, $data);
    }
    

Extension Points

  1. Custom Cache Store Override the default Redis store by binding a custom Illuminate\Contracts\Cache\Store in config/cache.php.

  2. Add Serialization Logic Extend PersistHelper to handle non-serializable data:

    public function rememberCache($seconds, $data) {
        $serialized = serialize($data); // Custom logic
        return parent::rememberCache($seconds, $serialized);
    }
    
  3. Event-Based Invalidation Use Laravel events to flush tags:

    // In a service provider
    event(new CountryUpdated());
    Event::listen(CountryUpdated::class, function () {
        Cache::tags('countries')->flush();
    });
    
  4. Environment-Specific TTLs Override TTLs in .env:

    CACHE_TTL_DEFAULT=300  # 5 minutes
    CACHE_TTL_API=3600    # 1 hour
    

    Then modify PersistHelper to read these values.


Performance Considerations

  • Avoid Over-Tagging: Too many tags can bloat Redis. Use broad tags (e.g., api) for related keys.
  • Use rememberCacheForever Sparingly: Redis may still evict keys under memory pressure.
  • Compress Large Data: For big payloads, use gzip before caching:
    $compressed = gzcompress(serialize($data));
    Persist::rememberCache(3600, $compressed);
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle