如果查看Zend Db Adapter
AdapterServiceFactory,您会看到适配器配置仅指向一个键
'db'。这意味着它构建的适配器将始终使用此(唯一)配置密钥。
我建议您创建自己的工厂,如下所示:
namespace YourNamespace;use ZendServiceManagerFactoryInterface;use ZendServiceManagerServiceLocatorInterface;use ZendDbAdapterAdapter;class MyAdapterFactory implements FactoryInterface{ protected $configKey; public function __construct($key) { $this->configKey = $key; } public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Config'); return new Adapter($config[$this->configKey]); }}
在您的主模块(或任何其他模块)中,将以下内容添加到Module.php文件中,以将适配器工厂声明为Zend Service Manager:
use YourNamespaceMyAdapterFactory;use ZendModuleManagerFeatureServiceProviderInterface;class Module implements ServiceProviderInterface{//Previous prepublic function getServiceConfig(){ return array( 'factories' => array( 'myadapter1' => new MyAdapterFactory('dbconfigkey1'), 'myadapter2' => new MyAdapterFactory('dbconfigkey2'), ), );}//...
现在,全局配置应如下所示:
return array('dbconfigkey1' => array( 'driver' => 'Pdo', 'dsn' => 'mysql:dbname=my_db;host=localhost', 'driver_options' => array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF8'' ), 'username' => 'user', 'password' => '******',),'dbconfigkey2' => array( 'driver' => 'Pdo', 'dsn' => 'mysql:dbname=my_db2;host=localhost', 'driver_options' => array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF8'' ), 'username' => 'user', 'password' => '******',),);
要使用适配器,您需要使用服务管理器来调用它们:
从2.2版开始$adapter1=$serviceManager->get('myadapter1');$adapter2=$serviceManager->get('myadapter2');
现在,抽象服务工厂已成为zf2 Zend Db模块的一部分。可以在“ adapters”子键下添加多个配置键:
'db'=> array( 'adapters'=>array( 'adapter' => array( 'driver' => 'Pdo', 'dsn' => 'mysql:dbname=test;host=localhost', 'username' => 'readCredential', 'password' => '****' ), 'adapter2' => array( 'driver' => 'Pdo', 'dsn' => 'mysql:dbname=test;host=localhost', 'username' => 'rwCredential', 'password' => '****' ), )),
但是,需要“手动”添加AbstractServiceFactory,因为默认情况下并非如此:
'service_manager' => array( 'abstract_factories' => array( 'ZendDbAdapterAdapterAbstractServiceFactory', )),
可以像以前一样访问适配器:
$adapter1=$serviceManager->get('adapter');$adapter2=$serviceManager->get('adapter2');
从性能角度来看,第二种方法更好:将实例化一个对象(抽象工厂)以(可能)创建不同的适配器。而在以前的方法中,每个配置创建一个对象。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)