krak/cache-buster

Cache Busting and Asset Versioning Library

v0.1.1 2016-05-01 07:19 UTC

This package is not auto-updated.

Last update: 2024-11-03 09:51:48 UTC


README

The Cache Buster library is used to break cache for assets that change.

Usage

The cache buster is a two part system where the bust-cache program will generate a config file of the new file info. You then need to utilize that file info in your codebase.

CLI

use ./bin/bust-cache for an interface and help on using the cache buster.

Also, you can register the Krak\CacheBuster\Command\BustCacheCommand in your own console applications like so.

<?php

// app is an instance of Symfony Console Application
$app->addCommand(new Krak\CacheBuster\Command\BustCacheCommand());

Code

Cache Buster provides a CacheBusterVersionStrategy in order to integrate with Symfony's Asset Component.

You just pass in the path to the config file.

<?php

use Krak\CacheBuster\Asset\CacheBusterVersionStrategy,
    Symfony\Component\Asset\Package;

$config = $is_prd_environment ? require __DIR__ . '/path/to/config.php' : [];
$package = new Package(new CacheBusterVersionStrategy($config));

echo $package->getUrl('/project.js');
// outputs the cache-busted file name

NOTE: For dev environments where cache busting might not be used, just pass in an empty array which will always trigger the decorated version strategy instance.

Symfony Asset Integration

If you already use the Symfony Asset library in your project, then you can pass a version strategy to the second argument of the CacheBusterVersionStrategy in order to decorate your version strategy.

<?php

use Krak\CacheBuster\Asset\CacheBusterVersionStrategy,
    Symfony\Component\Asset;

$vs = new Asset\VersionStrategy\StaticVersionStrategy('v1');
$package = new Package(new CacheBusterVersionStrategy($config, $vs));

Then any resources/files that aren't in the cache bust config will just pass through the wrapped version strategy instance. If no version strategy is used, it will default to using an EmptyVersionStrategy