我想在 Zend Framework 2 中设置 DB ADAPTER,就像在 Zend Framework 1 中设置 DB ADAPTER 一样。
在 ZF1 bootstrap.php 中我已经
protected function _initDatabase() {
$this->bootstrap('db');
$dbResource = $this->getResource('db');
Zend_Registry::set(ESIGN_REGISTRY_KEY_DB, $dbResource);
}
和 application.ini
resources.db.adapter = "pdo_mysql"
resources.db.params.dbname = "DB NAME"
resources.db.params.host = "HOST"
resources.db.params.username = "DB USER"
resources.db.params.password = "DB PASSWORD"
在我的应用程序中我可以使用
$dbAdapter = Zend_Registry::get('db');
并获取数据库适配器。
请帮我在ZF2中配置它。 谢谢。
最佳答案
有几种方法可以做到这一点,这取决于您实际构建应用程序的方式。但以下假设您在配置文件中正确设置了数据库适配器的所有内容。
所以你可以在某个地方这样做,
use Zend\Db\TableGateway\Feature\GlobalAdapterFeature;
// note, $sm is the service manager here
GlobalAdapterFeature::setStaticAdapter($sm->get('adapter_alias_name'));
别名
在您的配置文件中设置,例如:
// both of these are from factories in the `service manager` key in the config file.
'aliases' => array(
'adapter_alias_name1' => 'Zend\Db\Adapter\Adapter1',
'adapter_alias_name2' => 'Zend\Db\Adapter\Adapter2',
)
无论如何,继续,获取您将使用的静态适配器:
\Zend\Db\TableGateway\Feature\GlobalAdapterFeature::getStaticAdapter();
这可能就是您所需要的,但您也可以创建一个模型可以扩展的类,其中包含数据库适配器。
例如:
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\TableGateway\Feature\RowGatewayFeature;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\TableGateway\Feature;
abstract class AbstractTable extends AbstractTableGateway
{
public function __construct()
{
$this->featureSet = new Feature\FeatureSet();
$this->featureSet->addFeature(new Feature\GlobalAdapterFeature());
$this->featureSet->addFeature(new Feature\RowGatewayFeature($this->primary));
$this->featureSet->setTableGateway($this);
$this->featureSet->apply('preInitialize', array());
// view your adapter settings
echo '<pre>' . print_r($this->adapter, true) . '</pre>;die;
}
}
然后您的模型可以扩展该类,并且适配器已经设置。希望这是有道理的并能帮助一些人。我见过很多不同的实现方式。
关于php - Zend Framework 2 数据库适配器设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23409490/