Для подключения нескольких баз данных в то время, выполните следующие действия:
Шаг 1 :
Создать/модуль/MyModule/и добавить в application.config.ini для доступа.
Шаг 2: Создание module.php в/модуля/MyModule/директории со следующими сценариями
<?php
namespace MyModule;
use MyModule\MyAdapterFactory;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
class Module implements ServiceProviderInterface{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__.'/Db/Adapter/',
),
),
);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'adapter1' => new MyAdapterFactory('db_adapter1'),
'adapter2' => new MyAdapterFactory('db_adapter2'),
),
);
}
}
Шаг 3:
Создание MyAdapterFactory.php в пути:/модуль/MyModule/src/MyModule/Db/Adapter/со следующими скриптами.
<?php
namespace MyModule;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Db\Adapter\Adapter;
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]);
}
}
?>
Шаг 4:
Добавьте следующие скрипты в вашем getServiceConfig().
'YourModule\Model\YourTable' => function($sm) {
$tableGateway = $sm->get('YourTableGateway');
$table = new YourTable($tableGateway);
return $table;
},
'YourTableGateway' => function ($sm) {
$adapter1 = $sm->get('adapter1');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new YourModel());
return new TableGateway('tbl_name', $adapter1, null, $resultSetPrototype);
},
Шаг 5:
метод Add в контроллер, чтобы получить доступ к таблице, как показано ниже:
Объявите это на старте класса:
защищенный $ this-> yourTable ;
public function getYourTable()
{
if (!$this->yourTable) {
$sm = $this->getServiceLocator();
$this->yourTable = $sm->get('YourModule\Model\YourTable');
}
return $this->yourTable;
}
Затем, Вы можете позвонить модельных методов Select, Update, Insert, используя эту функцию (getYourTable()) в контроллере.
Спасибо, это помогло! – Tounu
Little edit - in global.php Мне нужно добавить путь к классу: 'return new Zend \ Db \ Adapter \ Adapter ($ config ['db_two']);' – user2047861