//Module.php中的一段代码(项目是zend framework2官网上的简单例子)
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);
},
),
);
}
//zend framework3中的样子
public function getServiceConfig()
{
return [
'factories' => [
Model\AlbumTable::class => function($container) {
$tableGateway = $container->get(Model\AlbumTableGateway::class);
return new Model\AlbumTable($tableGateway);
},
Model\AlbumTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
],
];
}
$sm
What type is it?
Model\AlbumTableGateway::class
How do you understand this? The class AlbumTableGateway
does not appear in the entire project, only the class AlbumTable
自己找了一个相似的问题,原文在下面,翻译在更下面。
source: AlbumTableGateway in Zend Framework 2 User Guide
The best way to think of this is that ServiceManager's get() method takes a key value, not a class name. The key value needs to map to something that will result in a class instance being returned.
If the key is within the invokables section, then the ServiceManager will try to instantiate the string that the key points to on the assumption that it's a classname:
If the key is within the factories section, then the ServiceManager will execute the callback that the key points to and expect an object instance to be returned:
In general, you use a factory when you need to do something more than just instantiate a class - usually you need to set up the class with another dependency. If you just need to instantiate a class, use an invokable.
翻译:
最好这样想:
ServiceManager
的get()
方法接受一个键
而不是一个类名
,这个键
会去匹配invokables
或factories
中的元素并返回一个创建的对象。ServiceManager
的get()
方法接受一个键
而不是一个类名
,这个键
会去匹配invokables
或factories
中的元素并返回一个创建的对象。如果这个
键
是处于invocables
如果这个键
是处于invocables
的区域, 它就会实例化匹配到的那个类。如果这个
键
处于工厂里,就会通过键
指向的callback
函数实例化一个对象返回。(如果都没匹配到就报错了)
一般来说,只有当你不仅仅是实例化一个已存在的类,而是要去构建一个有其他依赖的类的时候才会使用
factories
,否则的话就用invokables
就好了