SlimPHP and Doctrine

Posted January 2, 2014

Ive been playing around with lots of micro frameworks recently. No real objective I just wanted to see what was possible.

Silex is a great mico framework. Its got the power of Symfony2 components and by updating the composer.json file you can get a very good proto type working quickly. It also supports out of the box ( Some small configuration required ). Twig, Doctrine session security etc etc.

For the purpose of my testing I wanted something a little more raw, So Slim PHP it was. I followed the initial documentation and got it up and running, Next I needed some database level. So I thought lets get Doctrine thrown into the mix. Possibly overkill for a playground project but I wanted to try :)

The first part was to update my composer.json file with the new dependency:

    "require": {
        "slim/slim": "2.*",
        "doctrine/orm": "2.4.*"

Then run composer update ( This updates the composer.lock file with the new versions and requirements ). Once this is done run composer install.

This has generated us a new autoload.php file within vendor and pulled down all of the required doctrine code and dependencies.

Next I created a small config file that contained my DB settings:

    $dbParams = ['driver' => 'pdo_mysql',
    'host' => 'localhost',
    'dbname' => 'blog',
    'user' => 'root',
    'password' => 'root'

$dev = true;

Then inside of the main index.php file ( For me this is inside an API folder as the entire backend was PHP and talking to Ember.js ). I added the following:

$entitiesPath  = array(__DIR__.'/Blog/Entity');
$config        = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($entitiesPath, $dev);
$entityManager = Doctrine\ORM\EntityManager::create($dbParams, $config);

Now to be able to use the Doctrine entity manager in my basic example I did this:

$app->get('/', function () use ($entityManager) {
    $sql = "SELECT * FROM posts";
    $stmt = $entityManager->getConnection()->prepare($sql);
    echo json_encode($stmt->fetchAll());

One part that I added was the “use” as this is a closure I had to pass Entity Manager instance to the function for it to execute.

I hope this helps.

You may also find these related posts interesting: Developer Book Club All hail Xdebug and lets let var dump die A new look and a cleanup of content plus good bye github pages. Docker and Docker Sync