Possible to change action class within Yii2?

2019-06-21 22:36发布

问题:

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?

回答1:

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.



回答2:

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.



标签: php yii yii2