Bug ? - DependencyInjection does not work with widgets

Hi all,

I followed the instructions here: DI container to Widget

So I created an ActionFilter following the guide:

class ActionTimeFilter extends ActionFilter


    private $_startTime;

    public function beforeAction($action)


        $this->_startTime = microtime(true);

        return parent::beforeAction($action);


    public function afterAction($action, $result)


        $time = microtime(true) - $this->_startTime;

        Yii::info("Action '{$action->uniqueId}' spent $time second.");

        Yii::$container->set('common\widgets\ActionTime', ['time' => $time]);

        return parent::afterAction($action, $result);



So in the afterAction I used the container to set the time configuration of the ActionTime widget.

Like in the guide.

But when I call the widget in the view:

<p class="pull-right"><?= ActionTime::widget() ?></p>

The value of time property is NULL!

Here is my widget:

class ActionTime extends Widget


    public $time;

    public function init()



        if ($this->time === null) {

            $this->time = 'n.a.';



    public function run()


        return Html::encode("Generated in {$this->time} seconds.");



It seems this is a bug, because it is not work as described in the guide. Or what do you think?

Because in the ActionFilter the value is okay, I debuged it. But when the ActionTime widget called it seems the value from the container is deleted.

Because ActionTimeFilter::afterAction() hasn’t been called yet.

Yes, you are right. I’ve seen this in my code too.

Alternative solutions:

  • Session: use session for the calculated time

  • Pass the starter time to the widget and the widget will be calculate the spent time.