2016-11-19 57 views
0

我的助手类的代码如下:如何获得在助手类的根路径 - Symfony2的

public function getPlaceholders() 
{ 
    try { 
     echo $this->getParameter('kernel.root_dir'); 
    } catch (ParseException $e) { 
     printf("Unable to parse the YAML string: %s", $e->getMessage()); 
    } 
    return $this->placeholders; 
} 

它返回如下错误:

Attempted to call an undefined method named "getParameter" of class "AppBundle\Helper\Placeholders". 

请咨询我就可以了。

+1

不存在于'Placeholders'类'getParameter'方法错误的手段。 – Federkun

+0

那么如何在我的助手类中使用getParameter? @Federkun –

+1

'getParameter'是一个容器的方法,只需在'Placeholder'中注入并使用它。 (http://stackoverflow.com/questions/17126277/how-to-give-container-as-argument-to-services) – Federkun

回答

1

注入容器

services: 
    app.helper.placeholders: 
     class: AppBundle\Helper\Placeholders 
     arguments: ['@service_container'] 

,并使用容器的存取方法参数:

namespace AppBundle\Helper; 

use Symfony\Component\DependencyInjection\ContainerInterface; 

class Placeholders 
{  
    private $container; 

    public function __construct(ContainerInterface $container) 
    { 
     $this->container = $container; 
    } 

    public function getPlaceholders() 
    { 
     $root_dir = $this->container->getParameter('kernel.root_dir'); 

     // ... 
+0

这很好,但我必须调用这是在控制器中,所以我写如下:$ placeholders = new Placeholders(); 所以我必须在新的占位符()中传递参数;方法,因为__construct有一个参数。 –

+1

我不是无所不知,你知道:'新的占位符($ this-> container)' – Federkun