Here's how to inject the project root into Symfony services:
1<?php 2 3class TemplateFileService 4{ 5 6 public function __construct( 7 #[Autowire('%kernel.project_dir%')] 8 private string $projectDir 9 )10 {}11 12 public function readFile(): void13 {14 // use $this->projectDir15 }16 17}
Here, we are using the Symfony autowire attribute. So, when Symfony resolves this service, it automatically replaces `$projectDir` with the correct value. I prefer this method to defining bind values in YAML. Note that with this method, you don't lose testability. In tests, you can inject whatever value you like if the class is created outside of Symfony. You can use this same technique for other kernel and environment variables as well. See Symfony autowiring docs for more information.
Comments