How to Use a Custom Version Strategy for Assets

How to Use a Custom Version Strategy for Assets

Asset versioning is a technique that improves the performance of web applications by adding a version identifier to the URL of the static assets (CSS, JavaScript, images, etc.) When the content of the asset changes, its identifier is also modified to force the browser to download it again instead of reusing the cached asset.

If your application requires advanced versioning, such as generating the version dynamically based on some external information, you can create your own version strategy.

Note

Symfony provides various cache busting implementations via the version, version_format, and json_manifest_path configuration options.

Creating your Own Asset Version Strategy

The following example shows how to create a version strategy compatible with gulp-buster. This tool defines a configuration file called busters.json which maps each asset file to its content hash:

  1. {
  2. "js/script.js": "f9c7afd05729f10f55b689f36bb20172",
  3. "css/style.css": "91cd067f79a5839536b46c494c4272d8"
  4. }

Implement VersionStrategyInterface

Asset version strategies are PHP classes that implement the Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface. In this example, the constructor of the class takes as arguments the path to the manifest file generated by gulp-buster and the format of the generated version string:

  1. // src/Asset/VersionStrategy/GulpBusterVersionStrategy.php
  2. namespace App\Asset\VersionStrategy;
  3. use Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface;
  4. class GulpBusterVersionStrategy implements VersionStrategyInterface
  5. {
  6. /**
  7. * @var string
  8. */
  9. private $manifestPath;
  10. /**
  11. * @var string
  12. */
  13. private $format;
  14. /**
  15. * @var string[]
  16. */
  17. private $hashes;
  18. /**
  19. * @param string $manifestPath
  20. * @param string|null $format
  21. */
  22. public function __construct($manifestPath, $format = null)
  23. {
  24. $this->manifestPath = $manifestPath;
  25. $this->format = $format ?: '%s?%s';
  26. }
  27. public function getVersion($path)
  28. {
  29. if (!is_array($this->hashes)) {
  30. $this->hashes = $this->loadManifest();
  31. }
  32. return $this->hashes[$path] ?? '';
  33. }
  34. public function applyVersion($path)
  35. {
  36. $version = $this->getVersion($path);
  37. if ('' === $version) {
  38. return $path;
  39. }
  40. return sprintf($this->format, $path, $version);
  41. }
  42. private function loadManifest()
  43. {
  44. return json_decode(file_get_contents($this->manifestPath), true);
  45. }
  46. }

Register the Strategy Service

After creating the strategy PHP class, register it as a Symfony service.

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\Asset\VersionStrategy\GulpBusterVersionStrategy:
    4. arguments:
    5. - "%kernel.project_dir%/busters.json"
    6. - "%%s?version=%%s"
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd"
    7. >
    8. <services>
    9. <service id="App\Asset\VersionStrategy\GulpBusterVersionStrategy">
    10. <argument>%kernel.project_dir%/busters.json</argument>
    11. <argument>%%s?version=%%s</argument>
    12. </service>
    13. </services>
    14. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Asset\VersionStrategy\GulpBusterVersionStrategy;
    4. use Symfony\Component\DependencyInjection\Definition;
    5. return function(ContainerConfigurator $configurator) {
    6. $services = $configurator->services();
    7. $services->set(GulpBusterVersionStrategy::class)
    8. ->args(
    9. [
    10. '%kernel.project_dir%/busters.json',
    11. '%%s?version=%%s',
    12. ]
    13. );
    14. };

Finally, enable the new asset versioning for all the application assets or just for some asset package thanks to the version_strategy option:

  • YAML

    1. # config/packages/framework.yaml
    2. framework:
    3. # ...
    4. assets:
    5. version_strategy: 'App\Asset\VersionStrategy\GulpBusterVersionStrategy'
  • XML

    1. <!-- config/packages/framework.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd
    7. http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    8. <framework:config>
    9. <framework:assets version-strategy="App\Asset\VersionStrategy\GulpBusterVersionStrategy"/>
    10. </framework:config>
    11. </container>
  • PHP

    1. // config/packages/framework.php
    2. use App\Asset\VersionStrategy\GulpBusterVersionStrategy;
    3. $container->loadFromExtension('framework', [
    4. // ...
    5. 'assets' => [
    6. 'version_strategy' => GulpBusterVersionStrategy::class,
    7. ],
    8. ]);

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.