如何从 Zendframework 2 中的控制器插件中获取控制器? [英] How to get controller from within controller plugin in zendframework 2?

查看:31
本文介绍了如何从 Zendframework 2 中的控制器插件中获取控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 zf2 中编写控制器插件.我使用以下方法从插件中获取控制器,但它返回 null.

I am writing a controller plugin in zf2. I use the following method to get controller from within plugin, but it returns null.

$controller = $this->getController()

有什么建议吗?

推荐答案

您的插件中有两个选项没有设置控制器.

There are two options for which you have no controller set in your plugin.

  1. 您在分派之前从插件管理器调用插件,因此尚未设置控制器
  2. 你在__construct()
  3. 期间调用插件内部的控制器
  1. You call the plugin from the plugin manager prior to dispatch, so no controller is set yet
  2. You call the controller inside the plugin during __construct()

对于第一个,一个典型的例子是模块类中的 onBootstrap() 方法,显然你没有控制器:

For the first one, a typical example is an onBootstrap() method in a module class where obviously you have no controller:

public function onBootstrap($e)
{
  $app = $e->getApplication();
  $sm  = $app->getServiceManager();

  $plugins = $sm->get('ControllerPluginManager');
  $plugin  = $plugins->get('my-plugin');

  // $plugin->getController() === null
}

这似乎是一个明显的例子,但在其他情况下,您会错误地假设控制器已经存在(例如,在应用程序运行期间,在路由阶段;调度仍然必须到来).

This seems an obvious example, but there are other occasions where you are mistakenly assuming a controller exists already (for example, during run of the application, at the route phase; the dispatch still has to come).

第二个例子是因为控制器注入了setter注入.setter 在构造后被调用.在伪代码中,会发生这种情况:

The second example is because the controller is injected with setter injection. The setter is called after construction. In pseudo code, this happens:

$plugin = new $class;
$plugin->setController($controller);

如果你有这样的插件:

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class MyPlugin extends AbstractPlugin
{
  public function __construct()
  {
    // $this->getController() === null
  }
}

您注意到在该阶段没有设置控制器.

You notice there is no controller set at that phase.

这篇关于如何从 Zendframework 2 中的控制器插件中获取控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆