Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2 - DI and having to inject table adapter into tables... tedious?

I just read the Rob Allen's akrabat ZF2 tutorial (http://akrabat.com/wp-content/uploads/Getting-Started-with-Zend-Framework-2.pdf) on how to inject dependencies into your stuff like, injecting in your table adapter into your table classes.

This seems to be how I'm supposed to do it:

        array(
            'Application\Model\DbTable\UserTable',
        ) => array(
            'parameters' => array(
                'config' => 'Zend\Db\Adapter\PdoMysql',
            )
        ),

        array(
            'Application\Model\DbTable\UserProfileTable',
        ) => array(
            'parameters' => array(
                'config' => 'Zend\Db\Adapter\PdoMysql',
            )
        ),

Ok that's pretty cool but I've got around 84 tables so am I going to have to add each of these and say that I want PdoMySQL injecting into them all. Is there any proper way to do this such as specifying my entire DbTable folder? Not even this works:

        array(
            'Application\Model\DbTable\UserTable',
            'Application\Model\DbTable\UserProfileTable'
        ) => array(
            'parameters' => array(
                'config' => 'Zend\Db\Adapter\PdoMysql',
            )
        ),

Anyone else doing this and found a better solution?

Thanks, Dom

like image 818
Intellix Avatar asked Nov 15 '11 19:11

Intellix


1 Answers

Your question is a good one, and I agree, this a scenario where dependency injection does NOT make sense. I haven't browsed the ZF2 API yet, did they completely abandon the ability to bind adapter at the connection level, rather than the table level?

In my database class I use a yaml file to store connection settings; username, password, adapter, etc. I did it in a format which can be passed straight to Zend_Config, which can then be passed to the Zend_Db class.

// Entry in connection.yml
database:
  adapter: Pdo_Mysql
  params:
    host:     myhost
    dbname:   mydatabase
    username: myusername
    password: mypassword

// Parse yaml file to get above snippet in an array ($dbConnectionparams)

$config = new Zend_Config($dbConnectionParams);

$dbo = Zend_Db::factory($config->database);

Now, If I ever need to change the adapter for a database connection I only need to change it in one location, the connection.yml file.

Also, I believe you can store this type of connection data in various other formats (xml, etc).

like image 104
Mike Purcell Avatar answered Sep 23 '22 17:09

Mike Purcell