我目前有一个需要访问三个数据库表的ZF2模块。没有其他模块需要访问这些表。
所以我的问题是(请考虑表现)我应该像以前一样将工厂添加到Module.php:
/**
* Service Configuration
*
* @return array
*/
public function getServiceConfig()
{
return array(
'invokables' => array(
'Login\Service\Authenticate' => 'Login\Service\Authenticate',
'Login\Service\Oauth' => 'Login\Service\Oauth'
),
'factories' => array(
'Login\Form\Login' => function () {
$form = new Form\Login();
$form->setInputFilter(new FormFilter\Login());
return $form;
},
'Login\Model\GaclEmployeePermission' => function ($sm) {
return new Model\GaclEmployeePermission($sm->get('OTWebsoft\Db\Adapter\Master'), $sm->get('OTWebsoft\Db\Adapter\Slave'));
},
'Login\Model\Passport' => function ($sm) {
return new Model\Passport($sm->get('OTWebsoft\Db\Adapter\Master'), $sm->get('OTWebsoft\Db\Adapter\Slave'));
},
'Login\Model\PassportLog' => function ($sm) {
return new Model\PassportLog($sm->get('OTWebsoft\Db\Adapter\Master'), $sm->get('OTWebsoft\Db\Adapter\Slave'));
}
)
);
}
然后我有一个抽象类:
/**
* Table GaclEmployeePermission
*
* @return \Login\Model\GaclEmployeePermission
*/
protected function getTableGaclEmployeePermission()
{
return $this->getServiceManager()->get('Login\Model\GaclEmployeePermission');
}
或者我应该从Module.php中删除配置,在我的抽象类中只需执行此操作:
/**
* Table GaclEmployeePermission
*
* @return \Login\Model\GaclEmployeePermission
*/
protected function getTableGaclEmployeePermission()
{
return new GaclEmployeePermission($this->getMasterAdapter(), $this->getSlaveAdapter());
}
两者似乎完全相同。但是在性能方面,你会推荐哪种?请记住,这三个表不需要从任何其他模块访问,而是需要从这个模块访问。
答案 0 :(得分:1)
使用服务管理器或依赖注入容器的主要原因是不其他服务可以访问它。主要原因是应用依赖注入,从而应用控制反转。这样可以简化对象的使用,允许您轻松交换实现,增强测试类的能力,并使类对所包含的逻辑负责,而不会干扰其依赖性。
在这两个示例中,您实际使用的是服务管理器,但它仍然是相同的模式:类(在getTableGaclEmployeePermission()
内)决定要获取的内容。无论是通过服务管理器还是通过直接实例化,这实际上并不重要。
通过您的模块配置,我无法掌握您在应用程序中拥有的层以及它们的用途(尤其是关于该抽象类的内容),但一般来说,您应该注入它的依赖项:
abstract class SomeAbstract
{
protected $permission;
public function __construct(Permission $permission)
{
$this->permission = $permission;
}
}
class Permission
{
protected $master;
protected $slave;
public function __construct(TableAdapter $master, TableAdapter $slave = null)
{
$this->master = $master;
if (null !== $slave) {
$this->slave = $slave;
}
}
}
然后,您创建服务管理器配置以为您定义的服务注入这些依赖项:
'factories' => array(
'Login\Model\Permission' => function ($sl) {
$master = $sl->get('My\MasterAdapter');
$slave = null;
if ($some_flag) {
$slave = $sl->get('My\SlaveAdapter');
}
return new Login\Model\Permission($master, $slave);
},
'Login\Some\ConcreteImplementation' => function ($sl) {
$permission = $sl->get('Login\Model\Permission');
return new Login\Some\ConcreteImplementation($permission);
}
),
然后您请求Login\Some\ConcreteImplementation
并完成所有注射($master
,$slave
和$permission
),从而实现上述所有优势。