Brett
Brett

Reputation: 20049

Possible to change action class within 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?

Upvotes: 5

Views: 930

Answers (2)

Beowulfenator
Beowulfenator

Reputation: 2300

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.

Upvotes: 1

Estus Flask
Estus Flask

Reputation: 222760

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.

Upvotes: 1

Related Questions