这是您的用例的简单方法。我没有测试它,所以期待一些错别字:)
我希望你能得到基本的想法。如果没有,请告诉我。
配置/自动加载/auth.global.php
return [
'service_manager' => [
'factories' => [
'YourAuthNamespace\Config' => 'YourAuthNamespace\Service\ConfigServiceFactory',
'YourAuthNamespace\AbstractAuthFactoryFactory' => 'YourAuthNamespace\Service\AbstractAuthFactoryFactory',
],
'abstract_factories' => [
'YourAuthNamespace\AbstractAuthFactoryFactory'
]
]
];
src/YourAuth/Service/AbstractAuthFactoryFactory.php
namespace YourAuth\Service;
class AbstractAuthFactoryFactory implements \Zend\ServiceManager\AbstractFactoryInterface
{
public function canCreateServiceWithName(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$key = $this->getConfigKeyFromServiceName($name);
$config = $this->getConfig($serviceLocator);
return array_key_exists($key, $config);
}
private function getConfig(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator)
{
return $serviceLocator->get('YourAuthNamespace\Config');
}
public function createServiceWithName(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$key = $this->getConfigKeyFromServiceName($name);
$config = $this->getConfig($serviceLocator);
return new YourAuthClass($config[$key]);
}
private function getConfigKeyFromServiceName($name)
{
return preg_replace('#^YourAuthNamespace\Auth\#i', '', $name);
}
}
src/YourAuth/Service/ConfigServiceFactory.php
namespace YourAuth\Service;
use Zend\ServiceManager\FactoryInterface;
class ConfigServiceFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
return $config['yourauth'];
}
}
模块/MyModuleA/config/module.config.php
return [
'yourauth' => [
'ModuleA' => [ // 'ModuleA' is also the key used by the abstract factory
'db' => [
'table' => 'module_a_auth_table',
// ...
],
'session' => [
'namespace' => 'module_a_session_namespace'
// ...
],
]
],
'service_manager' => array(
'factories' => array(
'MyModuleA\Auth' => function ($sm) {
return $sm->get('YourAuthNamespace\Auth\ModuleA');
}
),
),
];
模块/MyModuleA/src/AuthClient.php
namespace MyModuleA;
class AuthClient implements \Zend\ServiceManager\ServiceLocatorAwareInterface
{
public function doSomethingWithAuth()
{
if ($this->getServiceLocator()->get('MyModuleA\Auth')->isAuthorized()) {
// blah...
}
}
}