2016-04-05 59 views
-1

我想在我的應用程序中使用自定義幫助程序。如何在symfony 2中聲明幫助程序

我創建的文件Myhelper.php捆綁/助手/ Myhelper.php與

namespace Project\Bundle\Helper; 

class Myhelper { 

    public function __construct($doctrine) { 

     $this->doctrine = $doctrine; 

    } 

    function testMyHelper() { 

     return "hi"; 

    } 

} 

我試圖把它叫在我的控制器:

$myHelper = $this->get('Myhelper'); 

但我有以下錯誤:

An exception has been thrown during the rendering of a template ("You have requested a non-existent service "myhelper".")

我必須在特定的配置文件中聲明它嗎?

Thx

回答

2

當您撥打$controller->get($id)功能時,它指的是通過給定的$id註冊的服務。如果你想在一個控制器來使用這個幫手,你需要將它註冊爲service.yml文件的服務(或XML,PHP,無論你使用的服務聲明)

# app/config/services.yml 
services: 
    app.helpers.my_helper: # the ID of the service user to get id 
     class:  Project\Bundle\Helper\MyHelper 
     arguments: ['@doctrine'] 

然後就可以調用$this->get('app.helpers.my_helper');獲得服務實例。

如果你想用它不控制,而且在樹枝,你需要注入它作爲一個樹枝延伸,並通過依賴注入注入你的服務:

# app/config/services.yml 
services: 
    app.twig_extension: 
     class: AppBundle\Twig\AppExtension 
     public: false 
     arguments: ['@app_helpers.my_helper'] 
     tags: 
      - { name: twig.extension } 

你可以在symfony中閱讀更多有關這Service container documentationTwig extension documentation

2

您應該在symfony上看到service的定義。 (請參閱:http://symfony.com/doc/current/book/service_container.html,其中詳細解釋瞭如何實施服務(由容器使用))。

您例如:

# app/config/services.yml 
 
services: 
 
    myhelper: 
 
     class:  YourClass 
 
     arguments: [@theservicedepedents]

然後通過$這個 - 把它在你的控制器>獲取( 'myhelper')

1

您嘗試使用輔助服務作爲。如果你想使用靜態方法創建助手類,你的實現將起作用。在你的例子中,你應該將課程註冊爲服務。如何運作你可以在官方symfony documentation閱讀服務。

0

我需要知道在哪種情況下你想使用助手?

Symfony的結構永遠不需要這種工具。 也許你在項目概念上有問題,或者你可能不知道某些工具。

+0

最後我用它作爲服務,它是從任何控制器填充數據庫中的通知 – Paul