2013-02-04 71 views
6

从控制器内部,我需要获取捆绑包内一个目录的路径。所以我有:在Symfony中获取捆绑包内的目录路径

class MyController extends Controller{ 

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

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

     // ... 
    } 
} 

如何得到正确$directoryPath

+0

./web/bundles/mybundle可以是一个符号链接到真正./mybundle/ressources/public文件夹,你可能有兴趣获得此代替路径。 –

+0

另外,我建议你从一个干净的服务定义的参数(例如“上传器”服务,而不是)设置$ directoryPath,这是symfony的方式。 –

回答

4

事情是这样的:

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

不幸的是你的代码会返回这个:“C:/ xampp/htdocs/projectname/app /../ web/bundles/mybundle/myfiles”! “..”不起作用! –

+0

@AliBagheriShakib我不使用Windows,但你可以通过使用dirname()来替换'/ ..':'dirname($ this-> container-> getParameter('kernel.root_dir')) 。 '/ web/bundles/mybundle/myfiles'' – ChocoDeveloper

+0

很棒的@ChocoDeveloper!这是windows上的工作。谢谢你... –

52

有一种更好的方式来做到这一点:

$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服务:file_locator。它在内部使用Kernel :: locateResource,但在测试中更容易加倍/模拟。

服务定义

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

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'); 
    } 
} 
+0

$ this-> container-> get('kernel') - > locateResource('@ AcmeDemoBundle/Resources /公共/ JS');会让你到Resources/public下的js目录的路径 - 而不是Resources的's'。 – Halfstop

+2

这应该是绝对接受的答案。 – Drumnbass