[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\DBAL\Types\ArticleType::TYPE_BLOG_POST
type_snippet: !php/const App\DBAL\Types\ArticleType::TYPE_SNIPPET
article_types: '%type_article%,%type_snippet%'
# This parameter can be used in annotations or attributes for example
article_requirements: '%type_article%|%type_snippet%'
Bonus, the snippet to run this code: 🎉<?php
declare(strict_types=1);
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\Integration\Controller\Snippets;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* @see Snippet49Trait
*/
final class Snippet49Test extends KernelTestCase
{
protected function setUp(): void
{
self::bootKernel();
}
/**
* @see Snippet49Trait::snippet49
*/
public function testSnippet49(): void
{
$articleTypes = self::getContainer()->getParameter('article_types');
$articleRequirements = self::getContainer()->getParameter('article_requirements');
self::assertSame('blog_post,snippet', $articleTypes);
self::assertSame('blog_post|snippet', $articleRequirements);
}
}
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
