[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\Repository\ArticleTypeRepository::TYPE_ARTICLE
    type_snippet: !php/const App\Repository\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 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'.PHP_EOL, 'article_types', $this->getParameter('article_types'));
        echo sprintf('%s: %s', 'article_requirements', $this->getParameter('article_requirements'));

        // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  Random snippet

<?php declare(strict_types=1);

namespace App\Tests\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @covers Snippet49Trait
 */
final class Snippet49Test extends KernelTestCase
{
    protected function setUp(): void
    {
        self::bootKernel();
    }

    /**
     * @covers Snippet49Trait::snippet49
     */
    public function testSnippet49(): void
    {
        $articleTypes = self::$kernel->getContainer()->getParameter('article_types');
        $articleRequirements = self::$kernel->getContainer()->getParameter('article_requirements');
        $this->assertSame('1,2', $articleTypes);
        $this->assertSame('1|2', $articleRequirements);
    }
}