7
votes

I'm trying to work effectively with DDD and Doctrine2 on a project with lot of business logic.

I understand that we need decouple the domain objects from other concepts related to the system, i.e. in a layered architecture, "the domain layer" must be isolate from other layers, like the persistence layer/service (Doctrine2 for me).

But there is one thing it's hard to understand for me: in several code examples of DDD with Doctrine 2, aggregates in domain entities are managed with Doctrine ArrayCollection, I found this kind of code :

namespace Acme\Domain\Model\Users;

use Doctrine\Common\Collections\ArrayCollection;

class User {

     //...

    /**
    * Collection of Roles
    *
    * @var Collection of Roles
    */
    protected $roles;

    /**
    * Constructor.
    */
    public function __construct()
    {
        $this->createdAt = new \DateTime();
        $this->roles = new ArrayCollection();
    }

    public function getRoles()
    {        
        return $this->roles;
    }
//...
}

For me, this implementation create a high coupling between domain models and the persistence service, Doctrine2.

On the other hand, if DDD Entity and Doctrine Entity classes are decoupled, there is to many layers/classes, in my opinion.

What do you think? Is there a better way to avoid/handle this?

1
You mentioned "lots of business logic". Consider starting a new question focusing on just one business rule that you feel might benefit from DDD.Cerad

1 Answers

6
votes

Don't be alarmed by the use of ArrayCollections. Notice that is in the Doctrine/Common namespace. It's just a little utility array wrapper with no particular ties to the Doctrine persistence layer. You could easily replace it with another array class.

The manual addresses this issue: https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#collections.

As far as decoupling goes, it is possible to do DDD modeling while limiting yourself to doctrine entities. It is very limiting and generally discouraged. So yep, you will probably need another layer.

It's difficult to justify the overhead of a pure DDD implementation in PHP.