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:

src/Service/MyCustomCacheStrategies.php
<?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
                    )
                ),
        ];
    }
}
circle-info

With service autoconfiguration enabled (default in Symfony), the tag spomky_labs_pwa.cache_strategy is added automatically. Otherwise, you need to tag your service manually.

Complete Example: Multiple Strategies

WorkboxCacheStrategy API

create()

Create a new strategy instance:

Available strategies:

  • CacheStrategyInterface::STRATEGY_CACHE_FIRST - Cache first, fallback to network

  • CacheStrategyInterface::STRATEGY_NETWORK_FIRST - Network first, fallback to cache

  • CacheStrategyInterface::STRATEGY_STALE_WHILE_REVALIDATE - Cache immediately, update in background

  • CacheStrategyInterface::STRATEGY_CACHE_ONLY - Cache only, never network

  • CacheStrategyInterface::STRATEGY_NETWORK_ONLY - Network only, never cache

Fluent Methods

Method
Description

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

Conditional Strategies

Create strategies that adapt based on conditions:

Implementing CacheStrategyInterface Directly

For complete control, implement CacheStrategyInterface directly to generate raw JavaScript:

circle-exclamation

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

  1. Open DevTools (F12) → ApplicationService Workers

  2. Click "Update" to reload service worker

  3. Check ApplicationCache Storage to see your custom caches

  4. Use Network tab with "Offline" to test cache behavior

Best Practices

  1. Start with YAML configuration: Only use custom strategies when necessary

  2. Use descriptive names: Make cache names clear (e.g., api-user-data not cache1)

  3. Set appropriate limits: Configure maxEntries and maxAgeSeconds to prevent cache bloat

  4. Test offline: Verify strategies work correctly without network

  5. Document complex logic: Add comments explaining why custom strategies exist

Last updated

Was this helpful?