Using Zend_Db With Silex

I’ve been messing around with Silex (and of course Symfony2) a lot lately, and I was excited to see a Doctrine extension. However, it was only for the DBAL and not the ORM. In my symfony2 apps, I’ve finally adjusted to using Doctrine’s ORM, but for some reason, I’ve really grown to like the DBAL that Zend_Db offers over the pseudo SQL (DQL) that Doctrine has. Here is a quick Extension to get you started with Zend_Db.

<?php
 
namespace SyndExtension;
 
use SilexApplication;
use SilexExtensionInterface;
 
class ZendDb implements ExtensionInterface
{
    public function register(Application $app)
    {
        $app['autoloader']->registerPrefix('Zend_', $app['zend.class_path']);
 
        $app['db'] = $app->share(function() use ($app) {
            return Zend_Db::factory($app['db.adapter'], array(
                'host'     => $app['db.host'],
                'dbname'   => $app['db.dbname'],
                'username' => $app['db.username'],
                'password' => $app['db.password']
            ));
        });
    }
}

Create that under ./src/Synd/Extension/ZendDb.php. To use it, you’ll need to add Synd to your autoloader, and then register the extension in your application:

$app['autoloader']->registerNamespace('Synd', 'src');
 
$app->register(new SyndExtensionZendDb(), array(
    'db.adapter'      => 'mysqli',    
    'db.dbname'       => 'your_db',
    'db.host'         => 'localhost',
    'db.username'     => 'root',
    'db.password'     => '',
    'zend.class_path' => '/path/to/zf/library'
));

Please note that this is a quick and dirty bridge, and is for ZF1 not ZF2. If I’m breaking any best practices with naming and combining libraries, be sure to let me know. I’m hoping to explore the Zend_Db and Zend_Form combination since I use them heavily in my apps. This provides a very lightweight infrastructure in order to throw up quick proof of concept applications.

Hopefully this helps someone… or at least gives enough familiarity for my ZF buddies to start looking at Silex / Symfony2.