【问题标题】:Zend Framwork 2 - mysqli connection configuration and testing exampleZend Framework 2 - mysqli连接配置及测试示例
【发布时间】:2013-09-28 01:41:27
【问题描述】:

我正在尝试通过给定的框架应用程序来学习 Zend Framework 2,但是我以前没有任何 Zend 经验。我确实从其他框架中了解 MVC,例如yii,symfony。

我的骨架应用程序似乎可以正常加载,那么下一步就是在应用程序中配置一个 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',
    ),
  ),
);

在 IndexController.php 文件中/module/Application/src/Application/Controller 的默认控制器中,我添加了以下内容来测试数据库,但我没有看到任何错误或来自该控制器的任何输出:

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!',
    ));
}

【问题讨论】:

  • 等待您的操作有什么输出吗?您是否尝试过回显 hello 以查看是否会打印?
  • 是的,它进入了正确的控制器,echo hello 正在打印,我们是否必须添加任何设置来添加新文件 db.local.php ?或者我还需要在配置中做些什么吗?
  • 确保您没有错过'service_manager' => array( 'factories' => array( 'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory', ), ), 部分。
  • :D 是的,这就是问题所在,我没有 'factories' => 数组('Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory'跨度>

标签: php zend-framework2 zend-db


【解决方案1】:

感谢 akond,实际问题看起来像我在服务管理器配置中创建了 db 对象的工厂。所以我必须将以下行添加到 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',
    ),
),

);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    相关资源
    最近更新 更多