Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to change action class within Yii2?

Tags:

php

yii

yii2

Is it possible to change the action class Yii2 uses somehow, similar to how you can set the class of many other components within the config file?

I want to extend this class so I can add another member variable to it.

I guess I could just add one to it anyway dynamically, but would prefer to do it in a proper fashion.

Edit: Looking at the list of core application components it isn't listed, so not sure if it's possible?

like image 652
Brett Avatar asked Oct 31 '22 22:10

Brett


2 Answers

The proper way to solve this problem is to extend both controller and action classes. If you look at the source code, yii\base\Controller has a createAction method that, if no class action is found, will create an instance of InlineAction.

Since you're extending some kind of controller class every time you make your own controller (class MyController extends Controller), you can just override the original createAction method and in it use your own implementation of the InlineAction class.

like image 72
Beowulfenator Avatar answered Nov 08 '22 14:11

Beowulfenator


It can be done with class map

Yii::$classMap['yii\base\InlineAction'] = '@common/InlineAction.php';

and should be placed into index.php, before the app is launched.

Regardless of its location, common/InlineAction.php should have the same yii\base namespace as the original class.

like image 37
Estus Flask Avatar answered Nov 08 '22 16:11

Estus Flask