DDD - Association mapping between bounded contexts using Doctrine 2

孤街浪徒 提交于 2021-02-18 12:50:28

问题


I am struggling to understand the right way to implement association mapping between two entities from different bounded contexts using Doctrine 2. Suppose that there are two "User" and "Post" entities that belong to "User" and "Content" bounded contexts, respectively. There is also a "User" concept in "Content" context that determines the author of a "Post" through a Many-To-One association. Therefore, "User" in "Content" context is simply a value object containing the user id.

My question is that how should I implement this association using Doctrine 2? I have two solutions that both have their own issues:

Solution 1:

/**
 * @ORM\Entity
 * @ORM\Table(name="posts")
 * @ORM\HasLifecycleCallbacks()
 */
 class Post
 {
    ...

    /**
     * @ORM\ManyToOne(targetEntity="UserBC\User", inversedBy="posts")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $user;

    ...
 }

Solution 2:

/**
 * @ORM\Entity
 * @ORM\Table(name="posts")
 * @ORM\HasLifecycleCallbacks()
 */
 class Post
 {
    ...

    /**
     * @ORM\Column(type="integer")
     */
    private $user_id;

    ...
 }

In the first solution, "User" entity from "User" context has been used inside "Content" context that violates DDD rules on BCs being independent of each other. The second solution respects DDD rules but affects database schema (removes database-level relationship between "users" and "posts" tables through a Foreign key constraint).

So, what is the right way to implement such associations?


回答1:


The second solution is correct.

As you correctly observe, associations between different BCs should be avoided. The right way to reference an entity in another BC is by ID.

This has the consequence that the BCs don't have constraints between them in the DB. After all, you try to make them independent. If you feel that this is wrong, then the only way around this is to reconsider your BC design, i.e. merge the two BCs. This is however a decision that should not be driven by code smells, but by your context map.

Note: Referencing entities from other BCs by ID is only allowed if they are aggregate roots. If the referenced entity is not an AR, you have another design smell right there. Not a serious one, but still one that needs consideration.



来源:https://stackoverflow.com/questions/34069203/ddd-association-mapping-between-bounded-contexts-using-doctrine-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!