DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
  • JQueue: A Library to Implement the Outbox Pattern
  • How to Integrate a Distributed Database With Event Streaming
  • Resilient Kafka Consumers With Reactor Kafka

Trending

  • Running Unit Tests in GitHub Actions
  • Bad Software Examples: How Much Can Poor Code Hurt You?
  • Modular Software Architecture: Advantages and Disadvantages of Using Monolith, Microservices and Modular Monolith
  • A Better Web3 Experience: Account Abstraction From Flow (Part 1)
  1. DZone
  2. Data Engineering
  3. Databases
  4. Service Injection in Doctrine DBAL Type

Service Injection in Doctrine DBAL Type

Emanuele Minotto user avatar by
Emanuele Minotto
·
Nov. 02, 13 · Interview
Like (0)
Save
Tweet
Share
6.99K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Doctrine (PHP) Database Event Injection

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

Opinions expressed by DZone contributors are their own.

Related

  • Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
  • JQueue: A Library to Implement the Outbox Pattern
  • How to Integrate a Distributed Database With Event Streaming
  • Resilient Kafka Consumers With Reactor Kafka

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: