2013-09-28 16 views
1

我正在嘗試通過給定的框架應用程序學習Zend Framework 2,但是我在Zend中沒有任何以前的經驗。我從其他框架知道MVC,例如yii,symfony。Zend Framwork 2 - mysqli連接配置和測試示例

我的骨架應用程序似乎加載正常,然後下一步是配置一個MySQL數據庫連接到應用程序。於是,我就以下問題的答案:

Zend Frameworkd 2 Database connection

但對我來說沒有工作,所以我想知道這是爲什麼。我的代碼是:

config/autoload/文件夾我創建了一個名爲db.local.php文件,並添加以下內容:

return array(
    'db' => array(
    'driver' => 'Mysqli', 
    'database' => 'xxx', 
    'username' => 'sxxx', 
    'password' => 'xxxE', 
    'hostname' => 'localhost' 
), 
    'service_manager' => array(
    'aliases' => array(
     'db' => 'Zend\Db\Adapter\Adapter', 
    ), 
), 
); 

而且在默認控制器/module/Application/src/Application/Controller文件IndexController.php我已經添加了以下測試分貝,但我沒有看到任何錯誤或任何輸出從該控制器:

public function indexAction() 
{ 
    $this->layout()->myvar = 'bla'; 

    $db=$this->getServiceLocator()->get('db'); 
    //var_dump($db); nothing comes here too. 

    $statement= $db->query('SELECT * FROM `ew_content` WHERE `con_id` = 1'); 
    var_dump($statement); // this also empty 

    $isconnected = $db->getDriver()->getConnection()->isConnected(); 
    if($isconnected){ 
     $message = 'connected'; 
    } else { 
     $message = 'not Valid data field'; 
    } 
    //no output here either 

    return new ViewModel(array(
     'customMessageForgotPassword' => 'Error!', 
    )); 
} 
+0

等待是什麼,從你的行動獲得輸出?你有沒有試過只是迴應'你好'看看是否打印? – Pankrates

+0

是的,它正確的控制器,回聲你好打印,我們必須添加任何設置來添加新的文件db.local.php?或者還有什麼我需要做的配置? – mahen3d

+0

確保你沒有錯過' 'service_manager'=>陣列( '工廠'=>陣列( 'Zend的\ DB \適配器\適配器'=> 'Zend的\ DB \適配器\ AdapterServiceFactory', ) '部分。 – akond

回答

1

感謝akond,實際的問題看起來像我有做一個工廠創建在服務管理配置數據庫對象。所以,我有以下行添加到db.local.php的配置

'service_manager' => array( 
    'factories' => array( 
     'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory', 
    ), 
), 

完整的工作代碼如下,

return array(
'db' => array(
    'driver'  => 'Mysqli', 
    'username'  => 'xxx', 
    'password'  => 'xxx', 
    'database'  => 'xxxx', 
    'host'   => 'localhost' 
), 
'service_manager' => array(
    'factories' => array(
      'translator' => 'MvcTranslator', 
      'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory', 
    ), 
    'aliases' => array(
     'db' => 'Zend\Db\Adapter\Adapter', 
    ), 
), 

);