11

From inside a controller I need to get the path of one directory inside a bundle. So 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 get correct $directoryPath?

2
  • ./web/bundles/mybundle can be a symlink to the real ./mybundle/ressources/public folder, you may be interested to get this path instead. Commented Jul 27, 2016 at 7:36
  • Also I recommend you to set $directoryPath from a parameter with a clean service definition (such an "Uploader" service instead), this is the symfony way. Commented Jul 27, 2016 at 7:38

2 Answers 2

86

There is a better way to do it:

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

will give an absolute path to AcmeDemoBundle

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

will give path to Resource dir inside AcmeDemoBundle, and so on...

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

Also, on a container definition, you can use:

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

EDIT

Your services don't have to depend on kernel. There is a default symfony service you can use: file_locator. It uses Kernel::locateResource internally, but it's easier to double/mock in your tests.

service definition

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

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'); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

$this->container->get('kernel')->locateResource('@AcmeDemoBundle/Resources/public/js'); Would get you to a path to the js directory under Resources/public - not the 's' for Resources.
2

Something like this:

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

2 Comments

Unfortunately your code will return this : "C:/xampp/htdocs/projectname/app/../web/bundles/mybundle/myfiles"! The ".." will not work!
@AliBagheriShakib I don't use Windows, but you can probably get around this by using dirname() to replace the '/..': dirname($this->container->getParameter('kernel.root_dir')) . '/web/bundles/mybundle/myfiles'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.