如果您想要一个适配器对象的集合,您可以将其建模为您向服务管理器注册的服务。
该服务是一个简单的集合类,称为DbAdapterCollection
. 每个适配器对象都由其名称存储和引用。
class DbAdapterCollection
{
protected $adapters = [];
public function __construct(array $adapters = [])
{
$this->setAdapters($adapters);
}
public function hasAdapter($name)
{
return isset($this->adapters[$name]);
}
public function getAdapters()
{
return $this->adapters;
}
public function setAdapters(array $adapters)
{
$this->adapters = [];
foreach ($adapters as $name => $adapter) {
$this->setAdapter($name, $adapter);
}
}
public function getAdapter($name)
{
if (! $this->hasAdapter($name)) {
throw new \RuntimeException('An adapter with the name \'' . $name . '\' could not be found.');
}
return $this->adapters[$name];
}
public function addAdapter($name, \Zend\Db\Adapter $adapter)
{
$this->adapters[$name] = $adapter;
}
}
要使用适配器对象填充此类,您可以使用服务工厂将它们注入到类__construct
中。我们可以使用服务管理器来加载所需的配置,这样我们就知道应该将哪些适配器添加到收集服务中。
class DbAdapterCollectionFactory
{
public function __invoke(ServiceManager $serviceManager, $name, $requestedName)
{
$config = $serviceManager->get('config');
$options = [];
$adapters = [];
if (isset($config['my_app']['services'][$requestedName])) {
$options = $config['my_app']['services'][$requestedName];
}
if (! empty($options['adapters']) && is_array($options['adapters'])) {
foreach ($options['adapters'] as $name => $adapter) {
if (is_string($adapter) && $serviceManager->has($adapter)) {
$adapter = $serviceManager->get($adapter);
}
if ($adapter instanceof \Zend\Db\Adapter) {
$adapters[$name] = $adapter;
}
}
}
return new DbAdapterCollection($adapters);
}
}
此示例的配置可能如下所示。
'service_manager' => [
'factories' => [
'DbAdapterCollection' => 'MyApp\\Db\\DbAdapterCollectionFactory'
],
],
// Example app config
'my_app' => [
'services' => [
'DbAdapterCollection' => [
// adapterName => dbServiceName,
'adapters' => [
'adapter1' => 'MyApp\\Db\\Adapter1'
'adapter2' => 'adapter2'
'adapter3' => 'adapter3'
],
]
],
],
然后,您只需要从服务管理器调用服务即可。
$adapterCollection = $serviceManager->get('DbAdapterCollection');
if ($adapterCollection->has('adapter1')) {
$adapter = $adapterCollection->get('adapter1');
}