Custom Cache Strategy
The bundle provides a comprehensive set of cache strategies through configuration. However, for advanced use cases requiring specific behaviors not covered by the YAML configuration, you can create custom cache strategies programmatically.
When to Use Custom Strategies
Use custom cache strategies when you need:
Dynamic behavior: Cache strategies that change based on runtime conditions
Complex matching logic: URL patterns too complex for regex or simple callbacks
Custom plugins: Workbox plugins with specific configuration
Conditional caching: Different strategies based on user state, headers, or other factors
Business logic integration: Caching tied to your application's domain logic
For most use cases, the YAML configuration and resource caching are sufficient.
Quick Start: Using WorkboxCacheStrategy
The easiest way to create custom cache strategies is using the WorkboxCacheStrategy helper class:
<?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 [
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()
Create a new strategy instance:
Available strategies:
CacheStrategyInterface::STRATEGY_CACHE_FIRST- Cache first, fallback to networkCacheStrategyInterface::STRATEGY_NETWORK_FIRST- Network first, fallback to cacheCacheStrategyInterface::STRATEGY_STALE_WHILE_REVALIDATE- Cache immediately, update in backgroundCacheStrategyInterface::STRATEGY_CACHE_ONLY- Cache only, never networkCacheStrategyInterface::STRATEGY_NETWORK_ONLY- Network only, never cache
Fluent Methods
withName(string)
Set a custom cache name
withMethod(string)
Specify HTTP method to intercept (e.g., 'POST', 'GET')
withPlugin(CachePluginInterface, ...)
Add one or more Workbox plugins
withPreloadUrl(string, ...)
Precache specific URLs on service worker install
withOptions(array)
Set additional Workbox options (e.g., networkTimeoutSeconds)
Available Workbox Plugins
ExpirationPlugin
Automatically remove old cache entries:
CacheableResponsePlugin
Control which responses get cached:
BroadcastUpdatePlugin
Notify clients when cached data updates:
Listen for updates in your application:
BackgroundSyncPlugin
Queue failed requests for retry when online:
RangeRequestsPlugin
Support HTTP range requests for large files:
Match Callback Patterns
The matchCallback parameter supports several formats:
Path Prefix
Regular Expression
Origin Match
Custom JavaScript Callback
Navigation Requests
Conditional Strategies
Create strategies that adapt based on conditions:
Implementing CacheStrategyInterface Directly
For complete control, implement CacheStrategyInterface directly to generate raw JavaScript:
When implementing the full interface, you're responsible for all JavaScript generation. This approach is powerful but requires careful testing.
Service Registration
If service autoconfiguration is disabled, register your service manually:
Listing Cache Strategies
Use the console command to list all registered cache strategies:
This displays all strategies (from YAML config and custom services) with their configuration details.
Debugging
Check Generated Service Worker
View the compiled service worker to see the generated JavaScript:
When debug is enabled, the generated code includes comments explaining each strategy.
Chrome DevTools
Open DevTools (F12) → Application → Service Workers
Click "Update" to reload service worker
Check Application → Cache Storage to see your custom caches
Use Network tab with "Offline" to test cache behavior
Best Practices
Start with YAML configuration: Only use custom strategies when necessary
Use descriptive names: Make cache names clear (e.g.,
api-user-datanotcache1)Set appropriate limits: Configure
maxEntriesandmaxAgeSecondsto prevent cache bloatTest offline: Verify strategies work correctly without network
Document complex logic: Add comments explaining why custom strategies exist
Related Documentation
Service Worker Configuration - Standard YAML configuration
Resource Caching - Configure caching via YAML
Custom Service Worker Rules - Advanced service worker customization
Last updated
Was this helpful?