Configuring Doctrine ORM in silex

By Jean Hertel, 15/02/2017, in category Tips

Doctrine, Doctrine ORM, Silex

Hello readers,

Today I'm going to show you a simple and easy way to configure Doctrine's ORM in the Silex framework.

By default, Silex already has a provider named DoctrineServiceProvider. This provider allows us to connect to a database with Doctrine DBAL. This by itself is already a hand in the wheel to have a better abstraction of the database, but does not give any significant improvement over the management of the created objects. For this purpose, there is Doctrine ORM, which encapsulates all this translation of database queries into php objects.

To install the ORM there are several options of providers, being possible to even configure everything at hand. For our example we will use the dFlyDev Doctrine ORM Service Provider.

First of all, install the package with the command:

composer install dflydev/doctrine-orm-service-provider

There are several configuration options, and I will not talk about all of them. The one I usually use is reading entities through annotations.

$app->register(new DoctrineOrmServiceProvider, [
  'orm.proxies_dir'             => 'src/App/Entity/Proxy',
  'orm.auto_generate_proxies'   => $app['debug'],
  'orm.em.options'              => [
    'mappings' => [
        'type'                         => 'annotation',
        'namespace'                    => 'App\\Entity\\',
        'path'                         => 'src/App/Entity',
        'use_simple_annotation_reader' => false,

With the above code we will register the ORM to read the annotations of the classes that are in the src/App/Entity directory with the App\Entity namespace.

Finally, Doctrine will not be able to locate our classes just with the above information, it needs a class Loader. Since we are using the composer, we can use its class Loader as follows:

use Doctrine\Common\Annotations\AnnotationRegistry;

$loader = require_once __DIR__ . '/vendor/autoload.php';
AnnotationRegistry::registerLoader([$loader, 'loadClass']);

You can see a complete and functional example here.