How Set Variable In Every Controller With Dependency Injection

Hello,

I have the following case: I want to put a variable in the constructor of any controller without making a new controller that inherits Yii controller.

I have the following code




class SiteController extends Controller

{

     public  $menuTop;


    public function actionIndex()

    {

        

        $this->menuTop = MenuCategories::getMenu(MenuCategories::TYPE_MENU_TOP);

        

        return $this->render('index', [

                   'handbook' => MenuCategories::getMenu(MenuCategories::TYPE_MENU_LEFT),

        ]);

    }

}



I want

variable does have it in each method and controller. For this purpose I want to use Dependency Injection, but I do not know how to do it

Generally, there are 2 main ways:

  1. Create a BaseController that the other controllers will extend from and set up the property in Controller::init().

  2. Create a Yii component

http://www.yiiframework.com/forum/index.php/topic/51624-how-to-create-and-use-components-in-yii2/page__view__findpost__p__239346

Not that I am helping you :) … but its better if you can go through a discussion on DI for Yii2 here