How to use the DataMapper pattern (Doctrine) in Slim

Intro

In today’s world of microservices, it is very important to simplify the process of creating API’s. In the same way we need a reliable tool that helps us to manage ingoing and outgoing data. These days you can find two main patterns, talking about relational databases, ActiveRecord and DataMapper. Personally, I prefer the latter, that’s why I show you today how to combine Doctrine with Slim.

Slim is a lightweight but powerful micro framework to create sites and RESTful applications.

Doctrine is an Object Relational Mapper (ORM) for PHP on top of a powerful database abstraction layer (DBAL). This is an implementation of DataMapper design  pattern, that also allows you to write queries in a proprietary SQL dialect called DQL ( doctrine query language) inspired by Hibernates HQL.

Let’s get started by installing Doctrine.

Installation

This step is as easy as adding this package to your composer

composer require doctrine/orm

But if you prefer to test the flavor of new Erdiko 2 beta version, in your project root directory run:

composer require erdiko/doctrine dev-erdiko2

It will install all dependencies.

Configuration

In this section we will set the basic settings needed by framework to know where and how load and use Doctrine.

It is easily accomplished by editing app/settings.php file in your Slim project. Please see example below:

<?php
'doctrine'=>[
   'meta'=>[
       'entity_path'=>[
           'app/src/Entity'
       ],
       'auto_generate_proxies'=>true,
       'proxy_dir'=> __DIR__.'/../cache/proxies',
       'cache'=>null,
   ],
   'connection'=>[
       'driver'  =>'pdo_mysql',
       'host'    =>'localhost',
       'dbname'  =>'your-db',
       'user'    =>'your-user-name',
       'password'=>'your-password',
   ]
]

Please don’t forget to replace each key with your customized values

In Erdiko 2, the configuration of basic settings work slightly different due to the project structure and the use of environment variables. However there is no need for panic as it is still accomplished very easily

The settings file is in bootstrap directory and it will return an array of settings mapping, but the actual definition will be place in config directory.

This is how settings looks like:

<?php
// All the settings needed to bootstrap your app and configure dependencies
return[
   'settings'=> [
       'displayErrorDetails'=>true,// set to false in production
       'addContentLengthHeader'=>false,// Allow the web server to send the content-length header

        // Renderer settings
       'renderer'=> [
           'template_path'=>'../app/templates',
       ],

       // Monolog settings
       'logger'=>requiregetenv("ERDIKO_ROOT").'/config/logger.php',

       // Theme settings
       'theme'=>requiregetenv("ERDIKO_ROOT").'/config/theme.php',

       // Database settings
       'database'=>requiregetenv("ERDIKO_ROOT").'/config/database.php',
   ],
];

For the database you’ll notice that the settings configurations for Slim and Erdiko 2 is almost the same as each other, except for Erdiko 2, that use getenv calls to retrieve values from the environment variable.

<?php
/* Database config */
return[
   'default'=>'master',
   'meta'=> [
       'entities'=> [
            getenv("ERDIKO_ROOT").'/app/entities'
       ],
       'is_dev_mode'=> getenv("ERDIKO_IS_DEV_MODE"),
       'cache'=>null,
   ],

   'connections'=> [
       'master'=> [
           'driver'=>'pdo_mysql',
           'host'=> getenv("DB_HOST"),
           'port'=> getenv("DB_PORT"),
           'database'=> getenv("DB_DATABASE"),
           'username'=>'root',
           'password'=> getenv("DB_PASSWORD"),
           'charset'=>'utf8',
           'collation'=>'utf8_unicode_ci',
           'prefix'=>''
       ]
    ]
];

Integration

Now that the settings file as been configured, you can integrate Slim / Erdiko 2 with Doctrine.

The first step, even though it is optional, is integrate the command line tool.  It is pretty handy.

The good news is you will have this tool available by just creating a single file, cli-config.php, in your config folder.

Please note that The Following example uses Erdiko 2’s folder structure to retrieve database settings.

<?php

useDoctrine\ORM\Tools\Console\ConsoleRunner;

requiredirname(__FILE__).'/../vendor/autoload.php';
$settings=includedirname(__FILE__).'/../config/database.php';

$config= \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(
   [$settings['meta']['entities']],
  null,
  null,
  null,
  false
);

$em= \Doctrine\ORM\EntityManager::create($settings['connections']['master'],$config);

returnConsoleRunner::createHelperSet($em);

In the example you’ll see that I’ve used Erdiko 2 folder’s structure to retrieve database settings.

Now you can see the available commands running in your project root folder:

php vendor/bin/doctrine

To create the entities you can choose to use the command line tool to create automatically. If you choose the manual option, you just need to follow doctrine’s conventions, here’s an example:

<?php
namespaceapp\entities;
/**
*@Entity @Table(name="test")
*/

classTest
{
   /**
     *@Id @GeneratedValue @Column(type="integer")
     *@varinteger
     */
   protected$id;

   /**
     *@Column(type="string")
     *@varstring
     */
   protected$name;

   /**
     *@Column(type="string")
     *@varstring
     */
   protected$description;

   public functiongetId()
   {
       return$this->id;
   }

   public functionsetId($id)
   {
       $this->id=$id;
   }

   public functiongetName()
   {
       return$this->name;
   }

   public functionsetName($name)
   {
       $this->name=$name;
   }

   public functiongetDescription()
   {
       return$this->description;
   }

   public functionsetDescription($description)
   {
       $this->description=$description;
   }
}

With the entities created, the final step is adding EntityManager in the dependencies which will vary on the place where dependencies file is. In Slim it’s placed in app/dependencies.php, and for Erdiko the content folder is bootstrap. Here’s an example (in Erdiko format):

<?php
...
// Doctrine
$container['em']=function($c){
   $settings=$c->get('settings');
   $config=\Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(
       $settings['doctrine']['meta']['entity_path'],
       $settings['doctrine']['meta']['auto_generate_proxies'],
       $settings['doctrine']['meta']['proxy_dir'],
       $settings['doctrine']['meta']['cache'],
       false
   );

   return\Doctrine\ORM\EntityManager::create($settings['doctrine']['connection'],$config);

};

And voila, it is ready to use.

Final Thoughts

Hope you have enjoyed reading and found this quick post useful. Comments and feedback are very welcome.

See you on the next post! In the meantime, take a look at our Github repo and all stars are much appreciated.

Next Post

Comments

See how we can help

Lets talk!

Stay up to date on the latest technologies

Join our mailing list, we promise not to spam.