好的,@Ocramius确实让我知道我对initializers
的误解是什么,并帮助我理解它。所以这里是解决你的问题的一个可能的解决方案。我对您的问题的理解是:
“如何为实现DbInterface的所有模型设置DbAdapter”。这是你会怎么做:
第1步:创建invokables
为实现DbInterface
所有类。默认Zend\Db\Adapter\Adapter
创建factory
,然后你DbInterface
模块创建initializer
。PHP getServiceConfig()
return array(
'invokables' => array(
'application-model-one' => 'Application\Model\One',
'application-model-two' => 'Application\Model\Two'
),
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory'
),
'initializers' => array(
'DbInterfaceInitializer' => function($instance, $sm) {
if ($instance instanceof \Application\Model\DBInterface) {
$instance->setDbAdapter($sm->get('Zend\Db\Adapter\Adapter'));
}
},
)
)
的的Zend \ DB \适配器\适配器使用顶级配置阵列密钥'db'
自动注入dbParams
步骤2:创建您的类实现您的接口
Application \ Model(One | Two | N).php
namespace Application\Model;
class One implements DbInterface, \Zend\Db\Adapter\AdapterAwareInterface
{
/**
* @var \Zend\Db\Adapter\Adapter $dbAdapter
*/
protected $dbAdapter;
public function setDbAdapter(\Zend\Db\Adapter\Adapter $dbAdapter) {
$this->dbAdapter = $dbAdapter;
}
public function getDbAdapter() {
return $this->dbAdapter;
}
// More of your business logic or data here
}
第3步:访问与服务定位这些课程从您的控制器
SomeController.php someAction()
$dbOne = $this->getServiceLocator()->get('application-model-one');
$dbTwo = $this->getServiceLocator()->get('application-model-two');
// Adapter will automatically be injected
当从的ServiceManager访问invokable
的initializer
将被调用。在初始化之后就会自动调用Zend\Db\Adapter\Adapter
,进而获取是从配置关键参数'db'
你可以从一次the tutorial Application获得更多的信息,以及对 samsonasik: ServiceManager Cheat-Sheet
来源
2013-02-13 07:56:20
Sam
的博客一旦DI是设置,我建议注入*每个*服务。 (并非所有的服务都是服务,但数据库访问肯定是!再次,我只在静态类型的环境中使用DI,所以我不需要担心使用恶意的“服务定位器模式”。) – 2013-02-12 22:55:49
如何设置这个DI虽然这是个问题?我已经看到无数关于注入到控制器的文章,这也意味着您必须将di添加到处理124个不同表的每个控制器中。现在看起来似乎不是一个非常可扩展的解决方案来使用DI,除非我完全误解了 – 2013-02-12 22:58:39
我不知道DI在PHP中是如何工作的,但如果做得对,它应该比使用'new's在那个地方。一旦它在任何地方使用,添加到任何特定服务的成本应该是微不足道的。如果CRUD是可预测的,那么寻找发电机可能是值得的。 – 2013-02-12 22:59:23