What is ValueObject in a Doctrine app with translations?

112 Views Asked by At

I have a table structure:

relation with page and title

Page can have many titles with different translations. In Symfony:

Model/Page.php - Main Page entity

Model/Page/PageFieldTitle.php - Entity for page_field_title table.

My first concern is what is a Value Object for title here? Got few concepts:

  1. Title is one, and Locale is second. Both value objects are used in PageFieldTitle entity
  2. Title is one, Locale is second, and there should be third: TitleLocalized that will use Title and Locale value objects. TitleLocalized will be used in PageFieldTitle entity.
  3. There should be Locale and TitleLocalized. TitleLocalized should have Locale and string inside. TitleLocalized will be used in PageFieldTitle entity.

1 - Separate value objects

Got implementation for this scenario.

class PageFieldTitle
{
    use PageFieldTrait;

    #[ORM\Embedded(columnPrefix: false)]
    protected PageTitle $value; // value object

    public function __construct(PageTitle $value, Locale $locale)
    {
        $this->setValue($value);
        $this->setLocale($locale);
    }

    public function getValue(): PageTitle
    {
        return $this->value;
    }

    public function setValue(PageTitle $value): PageFieldTitle
    {
        $this->value = $value;

        return $this;
    }
}

trait, so I can create more fields easily:

trait PageFieldTrait
{
    #[ORM\Id]
    #[ORM\ManyToOne(targetEntity: Page::class)]
    #[ORM\JoinColumn(name: 'page_id', referencedColumnName: 'id')]
    protected Page $page; // main Page entity

    #[ORM\Embedded(columnPrefix: false)]
    protected Locale $locale; // value object

    public function getLocale(): Locale
    {
        return $this->locale;
    }

    public function setLocale(Locale $locale): self
    {
        $this->locale = $locale;

        return $this;
    }

    public function setPage(Page $page): self
    {
        $this->page = $page;
        return $this;
    }
}

In Page entity got ManyToOne relation, and works fine.

2 and 3

Implementation is also possible, tested and I can use emedded objects inside embedded objects with doctrine. So every approach looks good.

Questions

  1. Which approach is best, and why?
  2. Is there any possibility to avoid using Model/Page/PageFieldTitle.php, which is only for holding value object? It's not easy to work with OneToMany relation for this.
0

There are 0 best solutions below