Best practice to call another controller action fr

2020-07-17 15:38发布

What is the best way of calling an action of another controller?

I am thinking in different options:

  1. Using forward plugin
  2. Setting the second controller as a dependency in the first controller

I think the first option will work but I would like to know if the second one has sense. In that case,

  1. How can I get the controller dependency?

I have tried to get it using the Service Manager but it isn't there. I have tried creating a Factory for the controller and get the another controller from the Controller Manager which is passed as an argument to the createService method when you implement the FactoryInterface. But it says that no controller is there. Exists a different locator from controllers than can be used in the same way as the Service Locator?

  1. The controller which has the role of dependency and will be called has to extends or implements any particular class or interface?

3条回答
仙女界的扛把子
2楼-- · 2020-07-17 15:57

To forward with parameters :

$this->forward()->dispatch('Namespace\Controller', array(
            'action' => 'ActionName',
            'params' => array(
                'id' => $id
            )
        ));
查看更多
时光不老,我们不散
3楼-- · 2020-07-17 16:01

I have found how to get ControllerManager in a controller:

<?php $cm = $this->serviceLocator->get('controllerManager');
查看更多
beautiful°
4楼-- · 2020-07-17 16:16

I would say that using the forward plugin is the ZF2 way to do it. This other solution that you propose sounds very complicated and might get you in all sorts of unsuspected trouble with dito bugs.

$this->forward()->dispatch('foo', array('action' => 'process'));

Or is there a reasonable argument why using this forward plugin is not what you want?

I actually don't understand why you can't get your other controller from your ControllerManager. Are you sure it is registered and that you use the correct name to get it?

查看更多
登录 后发表回答