2016-11-19 51 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