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.



// src/Entity/ArticleType.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\ArticleTypeRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

 * @ORM\Entity(repositoryClass=ArticleTypeRepository::class)
 * @ApiResource(
 *   attributes={"pagination_enabled"=false},
 *   normalizationContext={"groups"={""}},
 *   itemOperations={"get"},
 *   collectionOperations={"get"}
 * )
class ArticleType extends BaseEntity
    public const LABEL_MAX_LENGTH = 50; // must be public!

     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="IDENTITY")
    protected ?int $id = null;

     * @ORM\Column(name="label", type="string", length=App\Entity\ArticleType::LABEL_MAX_LENGTH, nullable=false)
     * Or the short notation is possible in this case:
     * #@ORM\Column(name="label", type="string", length=ArticleType::LABEL_MAX_LENGTH, nullable=false)

 More on Stackoverflow   Read the doc  Random snippet