在 Module.php 中配置 Table 的最佳方法 - Zend 2

Best way to configure a Table in Module.php - Zend 2

我正在使用 zend2 教程中的默认示例在 module.php 中设置我的表,但是在我的项目中我有太多表,所以我的 module.php 太大了。

这是我的默认配置示例 1:

            'UsersTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new Users());
                return new TableGateway('users', $dbAdapter, null, $resultSetPrototype);
            },
            'Application\Model\UsersTable'=>function ($sm){
                $tableGateway = $sm->get('UsersTableGateway');
                return new UsersTable($tableGateway);
            },

我的问题是,如果我像这样将 UserTableGateway 配置放入 Application\Model\UserTable 示例 2:

             'Application\Model\UsersTable'=>function ($sm){
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new Users());
                $tableGateway = new TableGateway('users', $dbAdapter, null, $resultSetPrototype);

                return new UsersTable($tableGateway);
            },

此方法适用于我,我的项目没有任何变化,不显示任何错误,项目继续正常工作。

所以,教程中的方式是说在单独的数组上设置 UserTableGateway?

如果我更改默认配置(上面的示例 1),在 Application\Model\Table 中设置全部(如上面的示例 2),是配置 tablesGateway 的好方法吗?是一个好习惯吗?

谢谢。

简而言之,您所做的很好,但我认为这不是最佳做法。

module.php 中配置服务并不是养成的最佳习惯,正如您所发现的那样,它很快就会变得非常混乱。更好的方向是利用ZF2的更多特性来帮助你解决困境。

让我们远离闭包。如果您的模型需要其他依赖项,最好创建 factories 并将您的 Application\Model\UsersTable 指向工厂 class 而不是闭包。例如,在您的 module.config.php:

'service_manager' => array(
    'factories' => array(
        'Application\Model\UsersTable' => 'Application\Model\Factory\UsersTableFactory'
    )
)

其中 Application\Model\Factory\UsersTableFactory 大致如下所示:

namespace Application\Model\Factory;

class UsersTableFactory
{
    public function __invoke(ServiceLocatorInterface $sl)
    {
        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
        $resultSetPrototype = new ResultSet();
        $resultSetPrototype->setArrayObjectPrototype(new Users());
        $tableGateway = new TableGateway('users', $dbAdapter, null, $resultSetPrototype);

        return new UsersTable($tableGateway);
    }
}

可以对您的所有模型以及您可能拥有的任何其他服务重复此操作。

需要考虑的事情

你提到你有很多表,我猜有很多模型。这将意味着很多工厂有很多重复代码,yuk。

这是我们可以使用abstract factories的地方。假设您的模型构造非常相似,我们可能只需要一个工厂就可以创建您所有的模型。

我不打算写一个这样的例子,因为它们可能会变得复杂,如果你自己调查一下会更好。简而言之,abstract factory 有两个工作:检查它是否可以创建服务,以及实际创建服务。