Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the path of a directory inside a bundle in Symfony

Tags:

symfony

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?

like image 770
Manuel Bitto Avatar asked Feb 04 '13 01:02

Manuel Bitto


2 Answers

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');
   }
}
like image 99
biera Avatar answered Oct 30 '22 19:10

biera


Something like this:

$directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/mybundle/myfiles';
like image 21
ChocoDeveloper Avatar answered Oct 30 '22 18:10

ChocoDeveloper