当前(2.1)ZF2用户指南的“Database and models”章节中有一段代码片段,我不明白:
( block “使用ServiceManager配置表网关并注入(inject)AlbumTable”)
...
class Module
{
// getAutoloaderConfig() and getConfig() methods here
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Album\Model\AlbumTable' => function($sm) {
$tableGateway = $sm->get('AlbumTableGateway');
$table = new AlbumTable($tableGateway);
return $table;
},
'AlbumTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
变量$sm
稍后将成为Zend\ServiceManager\ServiceManager
的实例,对吧? Zend\ServiceManager\ServiceManager#get(...) 方法需要类名作为第一个参数。但没有类AlbumTableGateway。只有两个模型类:Album\Model\Album 和Album\Model\AlbumTable。
这是指南中的错误还是我对代码的理解错误?
谢谢
最佳答案
最好的理解方式是 ServiceManager 的 get() 方法采用键值,而不是类名。键值需要映射到将导致返回类实例的内容。
如果键位于 invokables
部分中,则 ServiceManager 将尝试实例化键指向的字符串(假设它是类名):
'invokables' => array(
'some_name' => 'My\Mapper\SomeClassName',
),
如果键位于factories
部分中,则ServiceManager将执行键指向的回调并期望返回一个对象实例:
'factories' => array(
'some_name' => function($sm) { return new \My\Mapper\SomeClassName(); },
),
通常,当您需要执行的操作不仅仅是实例化类时,您可以使用工厂 - 通常您需要使用另一个依赖项来设置该类。如果您只需要实例化一个类,请使用可调用的。
关于zend-framework2 - Zend Framework 2 中的 AlbumTableGateway 用户指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15032330/