Zend Framwork 2 - mysqli connection configuration

2019-08-02 11:46发布

问题:

I am trying learn Zend Framework 2 via the skeleton application given, however I don't have any kind of previous experience in Zend. I do know about MVC from other frameworks e.g. yii, symfony.

My skeleton app seems to be loading fine, then the next step is to configure a MySQL db connection into the application. So I tried following question's answer:

Zend Frameworkd 2 Database connection

But that didnt work for me, so I am wondering why. My code is:

In the config/autoload/ folder I created a file called db.local.php and added the following:

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

And in the default controller in /module/Application/src/Application/Controller in file IndexController.php i have added the following to test the db, but I don't see any errors or any output from this 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!',
    ));
}

回答1:

thanks for akond, the actual issue looks like i have do a factory creation of the db object in the service manager config. So i have to add the following line to the db.local.php

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

full working code for the configuration is below,

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',
    ),
),

);