Custom Cache Strategies
When to Use Custom Strategies
Quick Start: Using WorkboxCacheStrategy
<?php
declare(strict_types=1);
namespace App\Service;
use SpomkyLabs\PwaBundle\CachingStrategy\CacheStrategyInterface;
use SpomkyLabs\PwaBundle\CachingStrategy\HasCacheStrategiesInterface;
use SpomkyLabs\PwaBundle\CachingStrategy\WorkboxCacheStrategy;
use SpomkyLabs\PwaBundle\WorkboxPlugin\ExpirationPlugin;
final readonly class MyCustomCacheStrategies implements HasCacheStrategiesInterface
{
/**
* @return array<CacheStrategyInterface>
*/
public function getCacheStrategies(): array
{
return [
// CacheFirst strategy for API data
WorkboxCacheStrategy::create(
enabled: true,
requireWorkbox: true,
strategy: CacheStrategyInterface::STRATEGY_CACHE_FIRST,
matchCallback: '({url}) => url.pathname.startsWith("/api/static/")',
)
->withName('api-static-data')
->withPlugin(
ExpirationPlugin::create(
maxEntries: 50,
maxAgeSeconds: 86400, // 1 day
)
),
];
}
}Complete Example: Multiple Strategies
WorkboxCacheStrategy API
create()
withName()
withMethod()
withPlugin()
withPreloadUrl()
withOptions()
Available Workbox Plugins
ExpirationPlugin
CacheableResponsePlugin
BroadcastUpdatePlugin
BackgroundSyncPlugin
Match Callback Patterns
1. Path Prefix
2. Regular Expression
3. Origin Match
4. Custom JavaScript Callback
5. Special Keywords
Advanced Example: Conditional Strategy
Real-World Use Cases
Use Case 1: Multi-tenant Application
Use Case 2: Authenticated API with Token Refresh
Use Case 3: Versioned API Endpoints
Implementing Custom Strategy Interface
Service Registration
Debugging Custom Strategies
1. Check Generated Service Worker
2. Enable Debug Mode
3. Chrome DevTools
Best Practices
Related Documentation
Last updated
Was this helpful?