Zend Framework 2 - Get Database access

Hey all,

Trying to wrap my head around the new concepts of Zend Framework 2.0.

I’m trying to connect to a database, and to get that connection in a controller or model.
Nothing fancy, just the pure connection to run queries against.

So this is my current code:


//module.config.php
return array(
    'db' => array(
        'driver'         => 'Pdo',
        'dsn'            => 'mysql:dbname=DBNAME;host=HOSTNAME,
        'driver_options' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \\'UTF8\\''
        ),
        'username' => 'USERNAME',
        'password' => 'PASSWORD',
    ),
    'service_manager' => array(
        'factories' => array(
            'translator' => 'Zend\\I18n\\Translator\\TranslatorServiceFactory',
            'Zend\\Db\\Adapter\\Adapter' => 'Zend\\Db\\Adapter\\AdapterServiceFactory',
        ),
    ),
);

What am I doing wrong?

Can I recommend Rob Allen’s “Getting Started with Zend Framework 2”, which is now officially part of the ZF2 documentation: http://zf2.readthedocs.org/en/latest/user-guide/overview.html

Work your way through that and all should become clear!

Admittedly I went through it around ZF2 beta 2 and haven’t touched ZF2 since, so I can’t recall the answer to your question, but I do know that you’ll be doing DB connections, selecting, inserting and updating as part of this guide. It doesn’t take long to run through

Thank you for the tip, I read it, but the problem is that it uses the TableGateway-classes/pattern, and I just want to do raw queries.

In the mean time, I found the answer for accessing the connection in the controller:

$adapter = $this->getServiceLocator()->get(‘Zend\Db\Adapter\Adapter’);

However, I still don’t know how to access the adapter in a custom class/model.
If somebody could explain that to me, would be great!

Ah, sorry I couldn’t be more help. It’s a framework that I’d really like to learn more about but time hasn’t allowed it yet.

If you get completely stuck, you could always tweet Rob and ask his advice :wink: https://twitter.com/akrabat