Possible to change action class within Yii2?

℡╲_俬逩灬. 提交于 2019-12-10 14:55:57

问题


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.



来源:https://stackoverflow.com/questions/31875638/possible-to-change-action-class-within-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!