且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ZF2 是否有更短/更简洁的方法来获取控制器中的 TableGateway 类?

更新时间:2023-11-28 15:49:22

控制器的理想设置方式是通过适当的(!)依赖注入.在 Zend Framework 2 中,您有两种主要方法可以在 ControllerManager 中声明控制器.第一个是invokables,用于没有依赖的控制器,第二个是factories,用于有依赖的控制器.

The way your Controllers should ideally be set up is through the means of proper(!) dependency injection. In Zend Framework 2 you have two main ways to declare controllers within the ControllerManager. The first one being invokables for controllers who have no dependencies and the second one being factories for controllers who have dependencies.

任何TableGateway 总是依赖.根据我的经验,根本没有可调用的控制器:P

Any TableGateway always is a dependency. To my experience there are no controllers who are invokables at all :P

有两种方法可以设置控制器工厂.

There's two ways to set up controller factories.

  1. Module.php 使用 getControllerConfig()
  2. controllers[factories] 项下,使用 Factory-Classes 输入您的 module.config.php
  1. Module.php using getControllerConfig()
  2. Under the controllers[factories] key in your module.config.php using Factory-Classes

为简单起见,我现在选择第一种方法:

For simplicity I'll choose the first approach now:

public function getControllerConfig()
{
    return array(
        'factories' => array(
            'My\Foo\Controller' => function ($cpm) {
                //@var $cpm \Zend\Mvc\Controller\ControllerManager
                $serviceLocator = $cpm->getServiceLocator();
                $tableGateway   = $serviceLocator->get('My\Table\Gateway');

                return new \My\Foo\Controller($tableGateway);
            }
        )
    );
}

有了这个,剩下的就是修改你的控制器并让它在其构造函数中传递相应的tablegateway:

With this, all that's left is for you to modify your controller and have it pass the respective tablegateway inside its constructor:

class Controller
{
    protected $tableGateway;

    public function __construct(\My\Table\Gateway $tg)
    {
        $this->tableGateway = $tg;
    }

    public function indexAction()
    {
        return new ViewModel(array(
            'entries' => $this->tableGateway->select()
        ));
    }
}

这就是全部.一切都与适当的依赖注入有关,它最终会让您的生活变得如此轻松.

And that's all there is to it. It's all about proper dependency injection that makes your life ultimately so much easier.

显然这个例子只覆盖了一个表,但是你可以通过构造函数传递更多的表来做同样的事情.也就是说:只有当你真的需要所有的 TableGateways 时(这听起来有点可疑);)

Obviously this example only covers one table, but you can do the same just passing more tables through the constructor. That is: only if you really need ALL TableGateways in there (which sounds a bit fishy) ;)