symfony 4 : How to get “/public” from RootDir

后端 未结 5 1624
孤街浪徒
孤街浪徒 2021-02-05 08:13

I have an image under the public folder.
How can I get my image directory in symfony4 ?
In symfony 3, it\'s equivalent is :

$webPath = $this         


        
相关标签:
5条回答
  • 2021-02-05 08:18

    It is a bad practice to inject the whole container, just to access parameters, if you are not in a controller. Just auto wire the ParameterBagInterface like this,

    protected $parameterBag;
    
    public function __construct(ParameterBagInterface $parameterBag)
    {
        $this->parameterBag = $parameterBag;
    
    }
    

    and then access your parameter like this (in this case the project directory),

    $this->parameterBag->get('kernel.project_dir');
    

    Hope someone will find this helpful.

    Cheers.

    0 讨论(0)
  • 2021-02-05 08:22

    You can use either

    $webPath = $this->get('kernel')->getProjectDir() . '/public/'; 
    

    Or the parameter %kernel.project_dir%

    $container->getParameter('kernel.project_dir') . '/public/';
    
    0 讨论(0)
  • 2021-02-05 08:22

    You can inject KernelInterface to the service or whatever and then get the project directory with $kernel->getProjectDir():

    <?php
    
    namespace App\Service;
    
    use Symfony\Component\HttpKernel\KernelInterface;
    
    class Foo
    {
        protected $projectDir;
    
        public function __construct(KernelInterface $kernel)
        {
            $this->projectDir = $kernel->getProjectDir();
        }
    
        public function showProjectDir()
        {
            echo "This is the project directory: " . $this->projectDir;
        }
    }
    
    0 讨论(0)
  • 2021-02-05 08:45

    In Controller (also with inheriting AbstractController):

    $projectDir = $this->getParameter('kernel.project_dir');
    
    0 讨论(0)
  • 2021-02-05 08:45
    parameters:
        webDir: '%env(DOCUMENT_ROOT)%'
    
    0 讨论(0)
提交回复
热议问题