Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Service Injection in Doctrine DBAL Type

DZone's Guide to

Service Injection in Doctrine DBAL Type

· DevOps Zone
Free Resource

The Nexus Suite is uniquely architected for a DevOps native world and creates value early in the development pipeline, provides precise contextual controls at every phase, and accelerates DevOps innovation with automation you can trust. Read how in this ebook.

get_preview

When you think of a Doctrine 2 DBAL Type you think of an atomic thing, but how can you work programmatically on this type without defining an event?

A DBAL Type doesn't allow access to the Symfony 2 service container, you must use a hack. But before this let me explain the classic way (using events), why you should use this hack and why you shouldn't.

The classic way is defined in the Symfony 2 Cookbook: How to Register Event Listeners and Subscribers

Doctrine 2 events unlike Symfony 2 events aren't defined by the developer, the developer can only attach listeners on them. Why? Because Doctrine 2 isn't a framework that you can use for everything, persistence is its only job.

When should you use this hack? When your stored object isn't a 1:1 representation of the PHP object and its elaboration can be memoizable or really fast.

I use this hack for browscaps: with the BrowscapBundle I can convert from an user agent string to a stdClass object (like the get_browser function).

Our object is

<?php
// src/Acme/DemoBundle/Entity/Agent.php
namespace Acme\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Table
* @ORM\Entity
*/
class Agent
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

/**
* @ORM\Column(name="header", type="string")
*/
private $header;
}

As you can see there's nothign special: it's just an archive used to store User-Agent strings.
With the classic way what I should do is write an external event listener (to allow automatic regeneration of entities).

services:
  acme.demo_bundle.event_listener.agent_listener
    class: "Acme\DemoBundle\EventListener\AgentListener"
    arguments:
      - "@service_container"
    tags:
      - { name: doctrine.event_listener, event: prePersist }
      - { name: doctrine.event_listener, event: postPersist }
      - { name: doctrine.event_listener, event: preUpdate }
      - { name: doctrine.event_listener, event: postUpdate }
      - { name: doctrine.event_listener, event: postLoad }

<?php
// src/Acme/DemoBundle/EventListener/AgentListener.php

namespace Acme\DemoBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Acme\DemoBundle\Entity\Agent;

class AgentListener
{
private $container;

public function __construct($container)
{
$this->container = $container;
}

public function prePersist(LifecycleEventArgs $args)
{
$this->doObjectToString($args);
}

public function postPersist(LifecycleEventArgs $args)
{
$this->doStringToObject($args);
}

public function preUpdate(LifecycleEventArgs $args)
{
$this->doObjectToString($args);
}

public function postUpdate(LifecycleEventArgs $args)
{
$this->doStringToObject($args);
}

public function postLoad(LifecycleEventArgs $args)
{
$this->doStringToObject($args);
}

private function doStringToObject($args)
{
$entity = $args->getEntity();

if ($entity instanceof Agent && !is_object($entity->getHeader())) {
$browscap = $this->container->get('browscap');
$browser = $browscap->getBrowser($entity->getHeader());
$entity->setHeader($browser);
}
}

private function doObjectToString($args)
{
$entity = $args->getEntity();

if ($entity instanceof Agent && is_object($entity->getHeader())) {
$user_agent = $entity->getHeader()->browser_name;
$entity->setHeader($user_agent);
}
}
}

With this code, everytime you will persist, update or extract a Agent entity from/to related storage system it'll be converted from string to object.

The problem is that these callbacks will be invoked everytime and numerous events aren't recommended for your application.

But with this hack I can write:

services:
  acme.demo_bundle.event_listener.container_listener:
    arguments:
      - "@service_container"
    class: "Acme\DemoBundle\EventListener\ContainerListener"
    tags:
      - { name: doctrine.event_listener, event: getContainer }

Doctrine ignores this event but it exists and results attached!

<?php
// src/Acme/DemoBundle/EventListener/ContainerListener.php

namespace Test\StorageBundle\EventListener;
use Symfony\Component\DependencyInjection\ContainerInterface;

class ContainerListener
{
private $container;

public function __construct(ContainerInterface $container)
{
$this->container = $container;
}

public function getContainer()
{
return $this->container;
}
}

This listener seems useless, but it's the only way for this hack because Doctrine 2 DBAL Type doesn't allow direct access to the service container but allows access to events listeners.

<?php
// src/Acme/DemoBundle/Types/BrowscapType.php

namespace Acme\DemoBundle\Types;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use phpbrowscap\Browscap;
use stdClass;

class BrowscapType extends Type
{
public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);
}

public function convertToPHPValue($value, AbstractPlatform $platform)
{
if (is_null($value)) {
return null;
}

$listeners = $platform->getEventManager()->getListeners('getContainer');

$listener = array_shift($listeners);
$container = $listener->getContainer();

return $container->get('browscap')->getBrowser($value);
}

public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value instanceof Browscap) {
return $value->getBrowser()->browser_name;
} elseif ($value instanceof stdClass) {
return $value->browser_name;
}

return $value;
}

public function getName()
{
return 'browscap';
}

public function requiresSQLCommentHint(AbstractPlatform $platform)
{
return true;
}
}

I use this hack to define only the events related to application flow (less events is better).

Now that you know when you can use this, you must read why you shouldn't use it.
Let me explain the reason with one simple example: imagine that one day PHP will allow external hooks in native classes constructor, how can you work without knowing what you're doing while initializing a new stdClass? The same reason here: everytime you extract a value from the database you want extract it fast (hopefully you'll extract more than one records), but how can you be sure that extraction is fast if every attribute of a single record depends on external libraries and logics?

Quoting Ocramius, member of the Doctrine 2 development team:

DBAL types are not designed for Dependency Injection.

We explicitly avoided using DI for DBAL types because they have to stay simple.

We’ve been asked many many times to change this behaviour, but doctrine believes that complex data manipulation should NOT happen within the very core of the persistence layer itself. That should be handled in your service layer.

The DevOps Zone is brought to you in partnership with Sonatype Nexus.  See how the Nexus platform infuses precise open source component intelligence into the DevOps pipeline early, everywhere, and at scale. Read how in this ebook

Topics:

Published at DZone with permission of Emanuele Minotto. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}