2016-12-06 88 views
0

我是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); 

訪問MySQL數據庫在每個控制器訪問數據庫的罰款。 (我想要一個配置。)

所以,我通過引導配置嘗試,

$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; 
    } 

如何訪問這個實例從 「」 檢索數據?

還是有其他解決方案嗎?

在此先感謝!

回答

0

通過適配器工廠

$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(); 

優勢這種方法現在可以解耦您的查詢,現在您可以將自定義邏輯正確地集成到您的模型上。

相關問題