LoginSignup
0
0

画像やCSSの管理、"Asset"

Last updated at Posted at 2023-12-06

Symfony Component Advent Calendar 2023の7日目の記事です。

画像やCSSの管理、"Asset"

Assetは、画像やCSSなどのファイルのバージョニングやURLの取得を行うコンポーネントです。

インストール

composer require symfony/asset

URLの取得

Package オブジェクトを作成し、getUrl()することで、ルートパスからのURLを取得できます。

use Symfony\Component\Asset\Package;
use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy;

$package = new Package(new EmptyVersionStrategy());
$url = $package->getUrl('/images/hoge.png');
// /images/hoge.png

バージョニング

上記だとただファイルのURLを取得しただけですが、Packageオブジェクトに渡すVersionStrategyクラスにより、バージョニングすることができます。ブラウザのキャッシュ対策に有効です。

  • EmptyVersionStrategy: バージョニングしない
  • StaticVersionStrategy: 指定した文字列でバージョニング
  • JsonManifestVersionStrategy: バージョニングされたJSONマニフェストを読み込む

StaticVersionStrategy

use Symfony\Component\Asset\Package;
use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy;

$package = new Package(new StaticVersionStrategy('v3'));
$url = $package->getUrl('/images/hoge.png');
// /images/hoge.png?v3

$package = new Package(new StaticVersionStrategy('v3'));
$url = $package->getUrl('/images/hoge.png', '%s?version=%s);
// /images/hoge.png?version=v3

JsonManifestVersionStrategy

manifest.json
{
    "js/hoge.js": "build/js/hoge.1234567890.js"
}
use Symfony\Component\Asset\Package;
use Symfony\Component\Asset\VersionStrategy\JsonManifestVersionStrategy;

$package = new Package(new JsonManifestVersionStrategy('./manifest.json'));
$url = $package->getUrl('/js/hoge.js');
// build/js/hoge.1234567890.js

また、VersionStrategyInterfaceを実装することで、カスタムのバージョニングを作ることもできます。

use Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface;

class DateVersionStrategy implements VersionStrategyInterface
{
    private \DateTimeInterface $version;

    public function __construct()
    {
        $this->version = date('Ymd');
    }

    public function getVersion(string $path): \DateTimeInterface
    {
        return $this->version;
    }

    public function applyVersion(string $path): string
    {
        return sprintf('%s?v=%s', $path, $this->getVersion($path));
    }
}

絶対パスによる取得

通常は相対パスですが、UrlPackageを使うことで絶対パスにもできます。

use Symfony\Component\Asset\UrlPackage;
use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy;

$package = new UrlPackage(
    'https://qiita.com',
    new StaticVersionStrategy('v3')
);
$url = $package->getUrl('/images/hoge.png');
// https://qiita.com/images/hoge.png?v3

まとめ

今回はAssetをご紹介しました。画像やCSSのキャッシュ対策にとても有効なコンポーネントになっていますが、後日紹介するあるコンポーネントと組み合わることで真価を発揮します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0