Answer the question
In order to leave comments, you need to log in
How to override a specific method from a module in Yii2?
The module has a controller that has a bunch of methods. I want to override one method without changing the code of the module itself. I seem to understand that this can somehow be done through the dependency injection container, but I don’t fully understand how. As an experiment, I created 2 test controllers NodeController and MyController, each of which has actionTest(). And I want to override actionTest() from NodeController to MyController, i.e. so that when this method is called from the NodeController controller ( myloc.ru:8080/node/test) , the same method is called, but from the MyController controller. I tried to do it through the construction in bootstrap.php :
Yii::$container->set(
'backend\controllers\NodeController',
'backend\controllers\MyController'
);
Answer the question
In order to leave comments, you need to log in
As far as I understand, you do not need to redefine the controller action, but replace it. Those. replace the action of one controller with the action of another controller. The task is doubtful, of course, but to solve it, you need to understand how requests are processed in Yii, namely:
1. The user sends a request to the server
2. Yii parses the request and determines which module / controller / action this request belongs to
3. Yii addresses the request to found in p2. controller action
Accordingly, in order to replace the request from /node/test to /my/test, it is enough to make adjustments to the URL parsing process, this can be done, for example, by creating the appropriate rule in the UrlManager of the application:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'node/test' => 'my/test' // все запросы с node/test переадресовывать на my/test
]
],
Добрый день.
<?php
class MyController extends NodeController
{
public function actionTest()
{
}
}
?>
why do that at all?
in the action actionTest NodeController
return Yii::$app->runAction('MyController/test');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question