How Set Variable In Every Controller With Dependency Injection


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

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