Yii2 Logo

Yii2 AssetBundle versioning

Yii2 Logo
Simple PHP class (extends Yii2 AssetBundle) that adds the file version in your assets URLs.

More info
http://www.yiiframework.com/doc-2.0/guide-structure-assets.html

<?php

namespace frontend\assets;

use yii\web\AssetBundle;

class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    
    public $cssFiles = [
        'css/site.css',
    ];
    
    public $jsFiles = [
        'js/libs.js'
    ];

    public $depends = [];

    public function init()
    {
        $this->css = $this->getVersionedFiles($this->cssFiles);
        $this->js = $this->getVersionedFiles($this->jsFiles);

        parent::init();
    }

    public function getVersionedFiles($files) 
    {
        $out = [];

        foreach ($files as $file) {
            $filePath = \Yii::getAlias('@webroot/' . $file);
            $out[] = $file . (is_file($filePath) ? '?v='.filemtime($filePath) : '');
        }

        return $out;
    }
}

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.