【问题标题】:How to declare an helper in symfony 2如何在 symfony 2 中声明一个助手
【发布时间】:2016-04-05 08:36:35
【问题描述】:

我想在我的应用程序中使用自定义助手。

我在 Bundle/Helper/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');

但我有以下错误:

在渲染模板期间抛出异常(“您请求了一个不存在的服务“myhelper”。”)

我必须在特定的配置文件中声明它吗?

谢谢

【问题讨论】:

    标签: symfony


    【解决方案1】:

    当您调用$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 上看到服务的定义。 (请参阅:http://symfony.com/doc/current/book/service_container.html,它准确解释了如何实现服务(由容器使用)。

      你的例子:

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

      然后通过 $this->get('myhelper') 在你的控制器中调用它

      【讨论】:

        【解决方案3】:

        您尝试将助手用作服务。如果您想使用静态方法将助手创建为类,您的实现将起作用。在您的示例中,您应该将类​​注册为服务。 How works services 你可以在官方 symfony documentation阅读。

        【讨论】:

          【解决方案4】:

          我需要知道在哪种情况下您要使用助手?

          Symfony 的结构永远不需要这种工具。 也许你在项目概念上有问题,或者你不知道一些工具。

          【讨论】:

          • 最后我把它作为一个服务使用,它是从任何控制器向数据库中填充通知
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-05-25
          • 2011-01-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多