LoginSignup
3
3

More than 5 years have passed since last update.

Yii 2.0.0 で独自のアセットクラスを作成するときの注意点

Last updated at Posted at 2014-11-23

Yii 2.0.0 限定ですが、独自のアセットクラスを作成するときにクロージャを使っているとデバッグモジュールが動作しないバグが発生します。issues にもあがっていますが (Debug toolbar doesn't load #5402) 、どういう場合に発生するか、またどう対処すればいいのかを簡単にですが書いていきます。

(2014/12/07 に 2.0.1 がリリースされました)

バグの再現例

例えば jquery-placeholder を使いたい場合、まず composer.json の require に追加して、composer update を実行。

composer.json
{
    "require": {
        "php": ">=5.4.0",
        "yiisoft/yii2": "*",
        ...
        "bower-asset/jquery-placeholder": "*"
    },
}

で、jquery-placeholder 用のアセットクラスを実装します。

JqueryPlaceholderAsset.php
<?php

namespace app\assets;

use yii\web\AssetBundle;

class JqueryPlaceholderAsset extends AssetBundle
{
    public $sourcePath = '@bower/jquery-placeholder';

    public $js = [
        'jquery.placeholder.js',
    ];

    public $depends = [
        'yii\web\JqueryAsset',
    ];

    public function init()
    {
        parent::init();

        $this->publishOptions['beforeCopy'] = function ($from, $to) {
            return basename($from) === 'jquery.placeholder.js';
        };
    }
}

sourcePath と js プロパティのみだと、発行されたアセットに必要のないものまで配置されちゃうので、init() メソッド内で発行する前のアセットから特定のファイルだけ抽出して配置させるようにしています (ここでクロージャを使用) 。上記の場合は 'jquery.placeholder.js' というファイルのみ配置されます。

とりあえず、jquery-placeholder 用のアセットが上手く発行されているのかを確かめるために assets/AppAsset の depends プロパティに JqueryPlaceholderAsset を追加。

AppAsset.php
<?php

namespace app\assets;

use yii\web\AssetBundle;

class AppAsset extends AssetBundle
{
    ...
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        'app\assets\JqueryPlaceholderAsset', // 追加
    ];
}

この状態で、ブラウザでページをロードすると読み込みが遅く、フッター辺りにあったデバッグモジュールもなくなっています。runtime/log/app.log を確認したところ yii\debug\LogTarget で warning が発生しています。

[warning][yii\log\Dispatcher::dispatch] Unable to send log via yii\debug\LogTarget: Exception 'Exception' with message 'Serialization of 'Closure' is not allowed'

対処

デバッグモジュールを使わなければ問題なさそうですが、そうもいかないので。

  • yiisoft/yii2-debug を dev-master にしてインストールする
  • 2.0.1 で修正済なのでそれを待つ (2014/12/07 に 2.0.1 がリリースされました)
3
3
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
3
3