在Module.php-Zend 2中配置表的最佳方法
我正在使用zend2教程中的默认示例在module.php中设置表,但是在我的项目中,我的表太多了,所以module.php太大了 以下是我的默认配置示例1:在Module.php-Zend 2中配置表的最佳方法,php,zend-framework2,Php,Zend Framework2,我正在使用zend2教程中的默认示例在module.php中设置表,但是在我的项目中,我的表太多了,所以module.php太大了 以下是我的默认配置示例1: 'UsersTableGateway' => function ($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new Resu
'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)设置all-in-Application\Model\Table(上面的示例2),那么配置TableGateway是一个好方法吗?这是一个好习惯吗
谢谢。简而言之,你做的很好,但我认为这不是最佳做法 在
module.php
中配置服务并不是最好的习惯,正如您所发现的,它很快就会变得非常混乱。更好的方向是使用ZF2的更多功能来帮助解决您的困境
让我们远离闭包。如果您的模型需要其他依赖项,最好创建工厂
,并将应用程序\Model\UsersTable
指向工厂类,而不是闭包。例如,在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
这是我们可以使用的地方。假设您的模型构造非常相似,我们可能只有一个工厂可以创建您的所有模型
我不打算写一个这样的例子,因为它们会变得复杂,如果你自己调查的话会更好。简而言之,
抽象工厂有两个任务:检查它是否可以创建服务,以及实际创建服务 仅就知识而言,当将服务配置为工厂时,我们必须在类中使用_construct()方法,如果您将它们设置为可调用,则将使用_invoke()。@rafaelphp对于工厂,我们有两个选项。我们可以实现FactoryInterface
并使用createService(ServiceLocatorInterface$sl)
或我的示例中使用的invoke方法。我同意了,因为它更简单。谢谢,帮了我大忙。