//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是什么类型?
Model\AlbumTableGateway::class这个怎么理解?整个项目中并没有出现AlbumTableGateway这个类,只有AlbumTable这个类
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
自己找了一个相似的问题,原文在下面,翻译在更下面。
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中的元素并返回一个创建的对象。如果这个
键是处于invocables的区域, 它就会实例化匹配到的那个类。如果这个
键处于工厂里,就会通过键指向的callback函数实例化一个对象返回。(如果都没匹配到就报错了)
一般来说,只有当你不仅仅是实例化一个已存在的类,而是要去构建一个有其他依赖的类的时候才会使用
factories,否则的话就用invokables就好了