代码之家  ›  专栏  ›  技术社区  ›  mahen3d

Zend Framwork 2-mysqli连接配置和测试示例

  •  1
  • mahen3d  · 技术社区  · 11 年前

    我正在尝试通过给定的框架应用程序学习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',
        ),
      ),
    );
    

    在中的默认控制器中 /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!',
        ));
    }
    
    1 回复  |  直到 11 年前
        1
  •  1
  •   mahen3d    11 年前

    感谢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',
        ),
    ),
    
    );