Using class constants in Doctrine annotations

Published on 2019-11-07 • Modified on 2019-11-07

This is a small trick to avoid putting raw values in your Doctrine annotations. For example, it is useful when you have a length constraint that can be shared among several fields and entities. You can also use these constants to create your form type constraints. Note that they must be public or you will get an error.


    private $label;

    // L1 to 28 used in templates/snippet/code/_53.html.twig

    public function __toString(): string
    {
        return $this->label;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getLabel(): ?string
    {
        return $this->label;
    }

    public function setLabel(string $label): ArticleType
    {
        $this->label = $label;

        return $this;
    }

    public function isArticle(): bool
    {
        return ArticleTypeRepository::TYPE_ARTICLE === $this->getId();
    }

    public function isSnippet(): bool
    {
        return ArticleTypeRepository::TYPE_SNIPPET === $this->getId();
    }
}