[Symfony] Using an application constant as a service container parameter

Published on 2019-10-25 • Modified on 2019-10-25

Sometimes you need to access an application's constant as a parameter in the container service file. You can directly use the PHP constant but if you use it in multiple places it can be better to introduce a container parameter you will be able to use everywhere and that is easier to access. For example, in this blog, I am using this trick to inject the locales' requirements in the controller's annotations: requirements={"_locale"="%locales_requirements%"}


# config/snippets/49.yaml
parameters:
    type_article: !php/const App\Entity\ArticleTypeRepository::TYPE_ARTICLE
    type_snippet: !php/const App\Entity\ArticleTypeRepository::TYPE_SNIPPET
    article_types: '%type_article%,%type_snippet%'
    # This parameter can be used in annotations for example
    article_requirements: '%type_article%|%type_snippet%'
Bonus, the snippet to run this code: 🎉
<?php declare(strict_types=1);

// src/Controller/Snippet/Snippet49Trait.php

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait in order to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet49Trait
{
    public function snippet49(): void
    {
        echo sprintf('%s: %s'."\n", 'article_types', $this->getParameter('article_types'));
        echo sprintf('%s: %s', 'article_requirements', $this->getParameter('article_requirements'));
        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc