如何在 symfony 2 中声明一个助手 [英] How to declare an helper in symfony 2
问题描述
我想在我的应用程序中使用自定义帮助程序.
I would like to use a custom helper in my application.
我在 Bundle/Helper/Myhelper.php 中创建了 Myhelper.php 文件
I created the file Myhelper.php in Bundle/Helper/Myhelper.php with
namespace Project\Bundle\Helper;
class Myhelper {
public function __construct($doctrine) {
$this->doctrine = $doctrine;
}
function testMyHelper () {
return "hi";
}
}
我试图在我的控制器中调用它:
And I tried to call it in my controller:
$myHelper = $this->get('Myhelper');
但我有以下错误:
在渲染模板期间抛出异常(您请求了一个不存在的服务myhelper".")
An exception has been thrown during the rendering of a template ("You have requested a non-existent service "myhelper".")
我必须在特定的配置文件中声明它吗?
Must I declare it in a specific config file ?
谢谢
推荐答案
当你调用 $controller->get($id)
函数时,它指的是由给定的 $ 注册的服务id
.如果你想在控制器中使用这个助手,你需要在 service.yml
文件(或 xml、php,无论你使用什么用于服务声明)中将它注册为服务
When you call $controller->get($id)
function it refers to a service registered by given $id
. If you want to use this helper in a controller you need to register it as a service in service.yml
file (or xml, php, whatever you use for service declarations)
# 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');
来获取服务实例.
Then you can call $this->get('app.helpers.my_helper');
to get the service instance.
如果你不想在控制器中而是在 twig 中使用它,你需要将它作为 twig 扩展注入并通过依赖注入注入你的服务:
If you want to use it not in controller but also in twig, you need to inject it as a twig extension and inject your service through dependency injection:
# app/config/services.yml
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
arguments: ['@app_helpers.my_helper']
tags:
- { name: twig.extension }
您可以在 symfony 服务容器文档 和
You can read more about this in symfony Service container documentation and Twig extension documentation
这篇关于如何在 symfony 2 中声明一个助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!