php - Zend Framework 2 数据库适配器设置

标签 php mysql zend-framework zend-framework2

我想在 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/

相关文章:

PHP xDebug图解读

php - 帮助按 id 显示 MySQL 数据库中的内容

mysql - 如何通过 'tag' 属性对数据库实体进行高级过滤

php - 如何在单个页面中提供驻留在 www 根目录之上的多个图像?

javascript - MySQL 的 %LIKE% 子句的 JavaScript 等价物是什么?

mysql - 本地电脑mysql80服务启动然后停止

php - Zend Framework 清除缓存

mysql - 从连接或子查询中选择记录作为列(子数组)

c# - 错误 :Additional information: Unexpected character encountered while parsing value: W. 路径 '',第 2 行,位置 1

php - 使用单引号或双引号插入或发布数据时出现问题