Yii2 Assets Cache

Hi,

started new basic Yii2 project, cache is disabled, Yii2 in DEV=true.

Assets management is through AssetBundle class (default basic app from composer).

Still it fails miserable.

After editing web/images/some.jpg it will render either old version or some crap like half of image.

After editing some CSS it does not update, browser says it is 304 (not modified)

Including JS and editing fails - some garbage or duplicated code added in the same edited js file.

Editing config/web.php values


'assetManager' => array(

            //'linkAssets' => true,

            'forceCopy' => true

        ),

does not help. Deleting web/assets/* Does not help either.

Tested on:

ubuntu,php55,nginx

docker,php54|php55,nginx

How to disable this "cache ?.." behavior and have a normal* DEV environment?..

  • By normal i mean "edit css|js|jpg, refresh, see results in browser".

Sure, because it shouldn’t. forceCopy is an option for publish(), not AssetManager’s property. The good question would be why AssetManager has no global options for bundles.

Anyway, if it’s your own asset bundle, you should add


public $publishOptions = ['forceCopy' => true];

to it, and doing this for Yii or third-party asset bundles may involve class extending and remapping, I guess.

Does not work.

That was comprehensive. Have you tried to clean cache or reload with ctrl+f5? Force copy of assets won’t help against caching behaviour of your browser. Yii obviously doesn’t handle Cache-Control for static stuff.

Well… this was much more deeper problem. I think there will be a lot of people with no clue.

Blog post: http://www.danhart.co.uk/blog/vagrant-virtualbox-modified-files-not-updating-via-nginx-apache

tl;dr

If you using Vagrant as virtual machine, set in your nginx config




sendfile off;



or apache:


EnableSendfile off

otherwise your static files will be "cached" with some random data and will be not updated after editing.

‘$forceCopy’ is value for AssetManager! \yii\web\AssetManager

You should not run it in production mode, only in dev as it is resource intensive on sites with traffic. You can specify it dynamically by detecting if Yii is in DEV mode:




    'components' => [

        'assetManager' => [

            'forceCopy' => YII_ENV_DEV ? true : false,

        ],

    ],



Rather than setting forceCopy to true, I just get around the issue by using symlinks to publish assets: http://www.yiiframework.com/doc-2.0/yii-web-assetmanager.html#$linkAssets-detail

Man, - you saved couple millions of my nerve cells!