简体   繁体   English

从ZF2中的控制器调用另一个控制器操作的最佳实践

[英]Best practice to call another controller action from a controller in ZF2

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. 我已经尝试为控制器创建一个Factory,并从Controller Manager获取另一个控制器,当您实现FactoryInterface时,它将作为参数传递给createService方法。 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? 具有依赖性并将被调用的控制器必须扩展或实现任何特定的类或接口?

To forward with parameters : 要转发参数:

$this->forward()->dispatch('Namespace\Controller', array(
            'action' => 'ActionName',
            'params' => array(
                'id' => $id
            )
        ));

I would say that using the forward plugin is the ZF2 way to do it. 我会说使用forward插件是ZF2的方法。 This other solution that you propose sounds very complicated and might get you in all sorts of unsuspected trouble with dito bugs. 你提出的另一个解决方案听起来非常复杂,可能会让你遇到各种各样的dito bug问题。

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

Or is there a reasonable argument why using this forward plugin is not what you want? 或者有一个合理的说法,为什么使用这个forward插件不是你想要的?

I actually don't understand why you can't get your other controller from your ControllerManager . 我实际上不明白为什么你不能从你的ControllerManager获得你的其他ControllerManager Are you sure it is registered and that you use the correct name to get it? 您确定它已注册并且您使用正确的名称来获取它吗?

我已经找到了如何在控制器中获取ControllerManager:

<?php $cm = $this->serviceLocator->get('controllerManager');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM