Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Frontend
  4. How to Use a Custom Version Strategy for Assets
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

Table of Contents

  • Creating your Own Asset Version Strategy
    • Implement VersionStrategyInterface
    • Register the Strategy Service

How to Use a Custom Version Strategy for Assets

Edit this page

Warning: You are browsing the documentation for Symfony 3.3, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

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
3
4
{
    "js/script.js": "f9c7afd05729f10f55b689f36bb20172",
    "css/style.css": "91cd067f79a5839536b46c494c4272d8"
}

Implement VersionStrategyInterface

Asset version strategies are PHP classes that implement the 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// src/AppBundle/Asset/VersionStrategy/GulpBusterVersionStrategy.php
namespace AppBundle\Asset\VersionStrategy;

use Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface;

class GulpBusterVersionStrategy implements VersionStrategyInterface
{
    /**
     * @var string
     */
    private $manifestPath;

    /**
     * @var string
     */
    private $format;

    /**
     * @var string[]
     */
    private $hashes;

    /**
     * @param string      $manifestPath
     * @param string|null $format
     */
    public function __construct($manifestPath, $format = null)
    {
        $this->manifestPath = $manifestPath;
        $this->format = $format ?: '%s?%s';
    }

    public function getVersion($path)
    {
        if (!is_array($this->hashes)) {
            $this->hashes = $this->loadManifest();
        }

        return isset($this->hashes[$path]) ? $this->hashes[$path] : '';
    }

    public function applyVersion($path)
    {
        $version = $this->getVersion($path);

        if ('' === $version) {
            return $path;
        }

        $versionized = sprintf($this->format, ltrim($path, '/'), $version);

        if ($path && '/' === $path[0]) {
            return '/'.$versionized;
        }

        return $versionized;
    }

    private function loadManifest()
    {
        return json_decode(file_get_contents($this->manifestPath), true);
    }
}

Register the Strategy Service

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

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
# app/config/services.yml
services:
    AppBundle\Asset\VersionStrategy\GulpBusterVersionStrategy:
        arguments:
            - "%kernel.project_dir%/busters.json"
            - "%%s?version=%%s"
        public: false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- app/config/services.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd"
>
    <services>
        <service id="AppBundle\Asset\VersionStrategy\GulpBusterVersionStrategy" public="false">
            <argument>%kernel.project_dir%/busters.json</argument>
            <argument>%%s?version=%%s</argument>
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
// app/config/services.php
use Symfony\Component\DependencyInjection\Definition;
use AppBundle\Asset\VersionStrategy\GulpBusterVersionStrategy;

$container->autowire(GulpBusterVersionStrategy::class)
    ->setArguments(
        array(
            '%kernel.project_dir%/busters.json',
            '%%s?version=%%s',
        )
)->setPublic(false);

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

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

    <framework:config>
        <framework:assets version-strategy="AppBundle\Asset\VersionStrategy\GulpBusterVersionStrategy" />
    </framework:config>
</container>
1
2
3
4
5
6
7
8
9
// app/config/config.php
use AppBundle\Asset\VersionStrategy\GulpBusterVersionStrategy;

$container->loadFromExtension('framework', array(
    // ...
    'assets' => array(
        'version_strategy' => GulpBusterVersionStrategy::class,
    ),
));
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:
Check Code Performance in Dev, Test, Staging & Production

Check Code Performance in Dev, Test, Staging & Production

Peruse our complete Symfony & PHP solutions catalog for your web development needs.

Peruse our complete Symfony & PHP solutions catalog for your web development needs.

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of Dalibor Karlović, a Symfony contributor

Thanks Dalibor Karlović for being a Symfony contributor

1 commit • 1 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia