Get directory path inside package in symfony

From inside the controller, I need to get the path to one directory inside the package. Therefore, I have:

class MyController extends Controller{ public function copyFileAction(){ $request = $this->getRequest(); $directoryPath = '???'; // /web/bundles/mybundle/myfiles $request->files->get('file')->move($directoryPath); // ... } } 

How to install $directoryPath correctly?

+6
source share
2 answers

Something like that:

 $directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/mybundle/myfiles'; 
+4
source

There is a better way to do this:

 $this->container->get('kernel')->locateResource('@AcmeDemoBundle') 

will give an absolute path to AcmeDemoBundle

 $this->container->get('kernel')->locateResource('@AcmeDemoBundle/Resource') 

will give the path to the dir resource inside AcmeDemoBundle and so on ...

An InvalidArgumentException will be thrown if such a file / file does not exist.

In addition, in the container definition, you can use:

 my_service: class: AppBundle\Services\Config arguments: ["@=service('kernel').locateResource('@AppBundle/Resources/customers')"] 

EDIT

Your services should not be kernel dependent. There is a default Symfony service that you can use: file_locator . It uses Kernel :: locateResource internally, but in your tests it is easier to double / layout.

service definition

 my_service: class: AppBundle\Service arguments: ['@file_locator'] 

the class

 namespace AppBundle; use Symfony\Component\HttpKernel\Config\FileLocator; class Service { private $fileLocator; public function __construct(FileLocator $fileLocator) { $this->fileLocator = $fileLocator; } public function doSth() { $resourcePath = $this->fileLocator->locate('@AppBundle/Resources/some_resource'); } } 
+52
source

All Articles