E
E
edik892016-12-06 12:36:24
Yii
edik89, 2016-12-06 12:36:24

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'
);

In this case, the call to myloc.ru:8080/node/test stops working and a 404 error is returned. How can this problem be solved?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2016-12-06
@edik89

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
    ]
],

Соответственно таким образом Вы можете подменять действия между контроллерами.
Если же есть необходимость подменить целый контроллер в модуле/приложении тогда стоит воспользоваться свойством controllerMap

Дмитрий, 2016-12-06
@slo_nik Куратор тега Yii

Добрый день.

<?php
class MyController extends NodeController
{
      public function actionTest()
      {

      }
}
?>

extends

D
developer007, 2016-12-06
@developer007

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 question

Ask a Question

731 491 924 answers to any question