Filter to add a variable to a view?

All,

I’ve been using Yii for a couple of years and just recently started working with Yii2. I love it! I had never used a filter before other than the Access Control filter but I thought it would be perfect for some code I wanted to execute for a number of actions on a controller. The purpose of the code was to pass a variable to the view without having to add the variable to each action in the controller.




namespace common\components;


use Yii;

use common\models\Model;

use yii\base\ActionFilter;


class TestFilter extends ActionFilter

{


    public function beforeAction($action)

    {

        $variable = Model::getdata();

        return parent::beforeAction($action);

    }


    public function afterAction($action, $result)

    {

        HOW DO I PASS $variable TO THE ACTION'S VIEW?

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

    }

}



Do you have any thoughts?

Take care,

-saniko

Found one way to do it using the view’s param array. However, I’m not sure if it is optimal. Can someone give me a best practice?




<?php


namespace common\components;


use Yii;

use common\models\Model;

use yii\base\ActionFilter;


class TestFilter extends ActionFilter

{


    public function beforeAction($action)

    {

        Yii::$app->view->params['variable'] = Model::getdata();

        return parent::beforeAction($action);

    }


}