简体   繁体   中英

Zend Framework 2: Database config

I'm digging into ZF2, and I've run into some confusion on how to use Zend\\Config with Zend\\Db to manually set up a connection.

In different places in the manual, there are db configs in different formats.

This one shows a flat array as the config format: https://packages.zendframework.com/docs/latest/manual/en/modules/zend.db.adapter.html

$adapter = new Zend\Db\Adapter\Adapter(array(
    'driver' => 'Mysqli',
    'database' => 'zend_db_example',
    'username' => 'developer',
    'password' => 'developer-password'
));

While this one shows a nested format: https://packages.zendframework.com/docs/latest/manual/en/modules/zend.config.introduction.html

$configArray = array(
    'database' => array(
        'adapter' => 'pdo_mysql',
        'params'  => array(
            'host'     => 'db.example.com',
            'username' => 'dbuser',
            'password' => 'secret',
            'dbname'   => 'mydatabase'
        )
    )
);

What I expect to happen is that I can call for a new db adapter like so, but this throws exceptions:

$config = new Zend\Config\Config(
    array(
        'db' => array(
            'adapter' => 'Mysqli',
            'params'  => array(
                'host'     => 'db.example.com',
                'username' => 'dbuser',
                'password' => 'secret',
                'dbname'   => 'mydatabase'
            )
        )
    )
);

$adapter = new Zend\Db\Adapter\Adapter($config->db);

What I end up having to do is:

$config = new Zend\Config\Config(
    array(
        'db' => array(
            'driver' => 'Mysqli',
            'host'     => 'db.example.com',
            'username' => 'dbuser',
            'password' => 'secret',
            'database'   => 'mydatabase'
        )
    )
);

$adapter = new Zend\Db\Adapter\Adapter($config->db->toArray());

Is there a better way of achieving what I'm trying to achieve without having to resort to the service manager?

Ignore the example from the Zend Config introduction page, that's just showing how to make a config object from a PHP array, the structure of the array isn't meant to show anything in particular.

Since you don't want to use the service manager, you need to pass the parameters to the adapter class in the structure it expects. It expects an array, a config object won't work. You've worked out what the structure of the array is, so that's what you need to use.

I think this page in the docs: http://framework.zend.com/manual/2.3/en/tutorials/tutorial.dbadapter.html (the "Basic setup" section) gives a better explanation of the service manager approach, which is how I'd do it in an MVC app at least.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM