9

I use Symfony 5 and Solarium. I want to get the project dir (or root dir) in my Controller (extends from AbstractController).

I saw some anwers with kernel, creating new services, etc..

But, isn't it just a function that call the project dir without creating some custom services etc..?

Thanks !

Brandys
  • 354
  • 1
  • 3
  • 15

2 Answers2

24

You don't need any service for this. You can get from container in your controller.

$this->getParameter('kernel.project_dir');

Other way is bind it on yaml.

    _defaults:
        bind:
            # pass this value to any $projectDir argument for any service
            # that's created in this file (including controller arguments)
            string $projectDir: '%kernel.project_dir%'

So you can inject each service and controller as $projectDir.

public class YourController {
   public function index(string $projectDir){
        // Your code
   }
}
public class YourService {
   public function __construct(string $projectDir){
        // Your code
   }
}

https://symfony.com/doc/current/configuration.html#accessing-configuration-parameters

tolgakaragol
  • 532
  • 4
  • 13
7

Since Symfony 6.1 you can autowire parameters
https://symfony.com/blog/new-in-symfony-6-1-service-autowiring-attributes

<?php
use Symfony\Component\DependencyInjection\Attribute\Autowire;

class MyService
{
    public function __construct(
        #[Autowire('%kernel.project_dir%/config/dir')]
        private $dir,
    ) {}
}
luchaninov
  • 6,792
  • 6
  • 60
  • 75