如何在Zend Framework中配置和访问MySQL数据库?

时间:2016-12-06 15:13:25

标签: php mysql zend-framework

我是Zend Framework的新手。

我尝试通过

访问MySQL数据库
    $db = new Zend_Db_Adapter_Pdo_Mysql(
        [
            'host' => 'localhost',
            'username' => 'user',
            'password' => 'pass',
            'dbname' => 'database'
        ]
    );
    $query = 'SELECT * FROM table_name';
    $this->view->rec = $this->db->fetchAll($query);

在每个控制器上访问数据库都很好。 (我想要单一配置。)

所以,我尝试通过 Bootstrap 配置,

   $this->bootstrap('db');
    switch (APPLICATION_ENV) {

        case 'development' :
            // this allows you to profile your queries through the firebug console
            $profiler = new Zend_Db_Profiler_Firebug('System Queries');
            $profiler->setEnabled(true);
            $this->getPluginResource('db')->getDbAdapter()->setProfiler($profiler);
            break;

        case 'production' :
            // if you use meta caching in production, which you should :)
            // Zend_Db_Table_Abstract::setDefaultMetadataCache($this->_cache);
            break;
    }

如何将此实例访问检索来自" 表格" ?

还是有其他解决方案吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

尝试通过Adapter Factory

设置默认适配器
$db = Zend_Db::factory('Pdo_Mysql', array(
'host'     => BASEHOST,
'username' => BASEUSR,
'password' => BASEPASS,
'dbname'   => BASE
));
Zend_Db_Table::setDefaultAdapter($db);

现在你可以为你的桌子建立一个模型

<?php
class YourTable extends Zend_Db_Table_Abstract{
  protected $_name = 'table' //your table;
}

最后获取数据

<?php
$model = new YourTable();
$this->view->red = $model->fetchAll();

此方法的优势现在是您可以解耦查询,现在您可以将自定义逻辑集成到您的模型上。