在Symfony中获取捆绑包中的目录路径

在Symfony中获取捆绑包中的目录路径,symfony,Symfony,从控制器内部,我需要获取捆绑包中一个目录的路径。因此,我: class MyController extends Controller{ public function copyFileAction(){ $request = $this->getRequest(); $directoryPath = '???'; // /web/bundles/mybundle/myfiles $request->files->ge

从控制器内部,我需要获取捆绑包中一个目录的路径。因此,我:

class MyController extends Controller{

    public function copyFileAction(){
        $request = $this->getRequest();

        $directoryPath = '???'; // /web/bundles/mybundle/myfiles
        $request->files->get('file')->move($directoryPath);

        // ...
    }
}
如何获得正确的
$directoryPath

类似这样:

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

有一种更好的方法:

$this->container->get('kernel')->locateResource('@AcmeDemoBundle')
将给出AcmeDemoBundle的绝对路径

$this->container->get('kernel')->locateResource('@AcmeDemoBundle/Resource')
将为AcmeDemoBundle中的资源目录提供路径,依此类推

如果该目录/文件不存在,将引发InvalidArgumentException

此外,在容器定义上,可以使用:

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

您的服务不必依赖于内核。您可以使用默认的symfony服务:文件定位器。它在内部使用Kernel::locateResource,但在测试中使用double/mock更容易

服务定义

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


不幸的是,您的代码将返回以下内容:“C:/xampp/htdocs/projectname/app/。/web/bundles/mybundle/myfiles”!“.”不起作用@AliBagheriShakib我不使用Windows,但您可能可以通过使用dirname()替换“/…”:
dirname($this->container->getParameter('kernel.root\u dir'))来解决这个问题/web/bundles/mybundle/myfiles'
$this->container->get('kernel')->locateResource('@AcmeDemoBundle/Resources/public/js');将使您找到Resources/public下js目录的路径-而不是资源的“s”../web/bundles/mybundle可以是指向实际的/mybundle/ressources/public文件夹的符号链接,您可能有兴趣获得此路径。此外,我建议您使用干净的服务定义(例如“上载器”)从参数设置$directoryPath服务),这是symfony的方式。
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');
   }
}