PHP code example of skaisser / laravel-cache-cascade

1. Go to this page and download the library: Download skaisser/laravel-cache-cascade library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

skaisser / laravel-cache-cascade example snippets


return [
    // Path for file-based cache storage
    'config_path' => 'config/dynamic',
    
    // Cache settings
    'cache_prefix' => 'cascade:',
    'default_ttl' => 86400, // 24 hours
    
    // Enable visitor-specific caching
    'visitor_isolation' => false,
    
    // Database integration
    'use_database' => true,
    'auto_seed' => true,
    
    // Define fallback order
    'fallback_chain' => ['cache', 'file', 'database'],
];

use Skaisser\CacheCascade\Facades\CacheCascade;

// Get data with automatic fallback
$data = CacheCascade::get('settings', []);

// Get with custom options
$faqs = CacheCascade::get('faqs', [], [
    'ttl' => 3600, // 1 hour
    'transform' => fn($data) => collect($data)->sortBy('order')
]);

// Set data (updates all layers)
CacheCascade::set('settings', $data);

// Clear specific cache (both methods work)
CacheCascade::clearCache('settings');
CacheCascade::forget('settings'); // Laravel-style alias

// Using the global helper
$settings = cache_cascade('settings', []); // Get with default
$value = cache_cascade('key', function() {  // Remember pattern
    return expensive_operation();
});

// Cache data with a callback (original method)
$users = CacheCascade::remember('active-users', function() {
    return User::where('active', true)->get();
}, 3600); // Cache for 1 hour

// Laravel-compatible signature with rememberFor()
$posts = CacheCascade::rememberFor('recent-posts', 3600, function() {
    return Post::recent()->limit(10)->get();
});

// Using the helper function
$data = cache_cascade('expensive-data', function() {
    return expensive_computation();
});

// Enable for specific cache
$userData = CacheCascade::get('user-settings', [], [
    'visitor_isolation' => true
]);

// Or use remember with isolation
$userDashboard = CacheCascade::remember('dashboard', function() {
    return $this->generateDashboard();
}, 3600, true); // Last parameter enables visitor isolation

// If 'faqs' table is empty, it will run FaqSeeder automatically
$faqs = CacheCascade::get('faqs');

// The package will look for:
// 1. Cache key 'cascade:faqs'
// 2. File at 'config/dynamic/faqs.php'
// 3. App\Models\Faq::orderBy('order')->get()
// 4. Database\Seeders\FaqSeeder (if auto_seed is enabled)

// config/dynamic/settings.php
 return [
    'data' => [
        'site_name' => 'My App',
        'maintenance_mode' => false,
    ]
];

use Skaisser\CacheCascade\Facades\CacheCascade;

// Invalidate all cache layers (cache + file)
CacheCascade::invalidate('settings');

// Refresh from database and update all layers
$freshData = CacheCascade::refresh('settings');



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Skaisser\CacheCascade\Traits\CascadeInvalidation;

class Faq extends Model
{
    use CascadeInvalidation;
    
    protected $fillable = ['question', 'answer', 'order'];
    
    // Optional: Customize the cache key (defaults to table name)
    public function getCascadeCacheKey(): ?string
    {
        return 'faqs'; // This will be the cache key
    }
    
    // Optional: Customize what data gets cached
    public function scopeForCascadeCache($query)
    {
        return $query->where('active', true)->orderBy('order');
    }
}

// This will automatically invalidate cache and file, then refresh from database
$faq = Faq::find(1);
$faq->update(['answer' => 'Updated answer']);

// Cache has been automatically refreshed!
$cachedFaqs = CacheCascade::get('faqs'); // Fresh data from database

// Manually refresh cache for a model
$faq = Faq::first();
$faq->refreshCascadeCache();

$products = CacheCascade::get('products', [], [
    'transform' => function($data) {
        return collect($data)
            ->map(fn($item) => new ProductDTO($item))
            ->filter(fn($product) => $product->isActive());
    }
]);

CacheCascade::set('config', $data, true); // Skip database

// Enable tags in config
'use_tags' => true,
'cache_tag' => 'my-app-cache',

// Clear all cascade caches
CacheCascade::clearAllCache();

use Skaisser\CacheCascade\Facades\CacheCascade;

// Get store configuration with fallback
$storeConfig = CacheCascade::get('store-config', [
    'currency' => 'USD',
    'tax_rate' => 0.08
]);

// Remember computed values with Laravel-compatible syntax
$shippingRates = CacheCascade::rememberFor('shipping-rates', 3600, function() {
    return ShippingProvider::calculateRates();
});

// Clear cache when admin updates settings
CacheCascade::forget('store-config');
CacheCascade::forget('shipping-rates');

// Enable visitor isolation for tenant-specific data
$tenantSettings = CacheCascade::remember('tenant-settings', function() {
    return Tenant::current()->settings;
}, 86400, true); // true enables visitor isolation

// Or use the global helper
$features = cache_cascade('tenant-features', function() {
    return Feature::forTenant(tenant())->get();
});

// Model with automatic cache invalidation
class Page extends Model
{
    use CascadeInvalidation;
    
    public function getCascadeCacheKey(): ?string
    {
        return 'pages';
    }
}

// Usage in controllers
$pages = CacheCascade::rememberFor('pages', 7200, function() {
    return Page::published()->with('author')->get();
});

// When a page is updated, cache automatically refreshes!
$page->update(['title' => 'New Title']); // Triggers cache invalidation

// Cache API responses with transformation
$apiData = CacheCascade::get('weather-data', [], [
    'ttl' => 1800, // 30 minutes
    'transform' => function($data) {
        return collect($data)->map(function($item) {
            return [
                'temp' => $item['temperature'],
                'desc' => $item['description'],
                'icon' => "weather-{$item['code']}.svg"
            ];
        });
    }
]);

// Refresh from external API
Route::post('/admin/refresh-weather', function() {
    $freshData = WeatherAPI::fetch();
    CacheCascade::set('weather-data', $freshData);
    CacheCascade::invalidate('weather-widget'); // Clear dependent caches
});

// Define feature flags that must always load
$features = CacheCascade::remember('feature-flags', function() {
    return FeatureFlag::all()->pluck('enabled', 'name');
}, 86400);

if ($features['new-checkout-flow'] ?? false) {
    return view('checkout.new');
}

// Admin panel update
Route::post('/admin/features/{flag}/toggle', function($flag) {
    FeatureFlag::where('name', $flag)->toggle('enabled');
    CacheCascade::refresh('feature-flags'); // Immediate update
});

// config/cache-cascade.php
'clear_on_cache_clear' => false,

use Skaisser\CacheCascade\Helpers\ConfigCacheHelper;

// Get all static config files (excluding cascade files)
$staticFiles = ConfigCacheHelper::getStaticConfigFiles();

// Get all cascade cache keys from file storage
$cascadeKeys = ConfigCacheHelper::getFileStorageKeys();

// .env
CACHE_CASCADE_LOG=true
CACHE_CASCADE_LOG_CHANNEL=daily
CACHE_CASCADE_LOG_LEVEL=debug

// config/cache-cascade.php
'logging' => [
    'enabled' => true,
    'channel' => 'daily',
    'level' => 'debug',
    'log_hits' => true,   // Log cache/file/database hits
    'log_misses' => true, // Log cache misses
    'log_writes' => true, // Log write operations
],

// Tenant settings always available, even if Redis is down
$settings = CacheCascade::get("tenant:{$tenantId}:settings");

class Article extends Model
{
    use CascadeInvalidation;
    
    // Article updates automatically refresh the cache
}

$products = CacheCascade::remember('products:list', function() {
    return Http::get('https://api.example.com/products')->json();
}, 3600);

class FeatureFlag extends Model
{
    use CascadeInvalidation;
    
    // Flags update instantly across all servers
}

// Even on fresh deployments, settings are auto-seeded
$shippingRates = CacheCascade::get('shipping:rates');

use Skaisser\CacheCascade\Facades\CacheCascade;

public function test_my_service()
{
    // Replace with fake for testing
    $fake = CacheCascade::fake();
    
    // Your code that uses CacheCascade
    $service = new MyService();
    $service->cacheSettings();
    
    // Assert cache interactions
    $fake->assertCalled('set', ['settings', $data, false]);
    $fake->assertHas('settings');
    
    // Verify call counts
    $this->assertEquals(1, $fake->calledCount('set'));
}
bash
php artisan vendor:publish --tag=cache-cascade-config
bash
# Refresh cache from database
php artisan cache:cascade:refresh {key}

# Clear specific or all cascade cache
php artisan cache:cascade:clear {key}
php artisan cache:cascade:clear --all

# Show cache statistics
php artisan cache:cascade:stats
php artisan cache:cascade:stats {key}
bash
php artisan cache:cascade:stats