Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

How to declare an helper in symfony 2

I would like to use a custom helper in my application.

I created the file Myhelper.php in Bundle/Helper/Myhelper.php with

namespace ProjectBundleHelper;

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');

But I have the following error:

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 ?

Thx

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:        ProjectBundleHelperMyHelper
        arguments:    ['@doctrine']

Then you can call $this->get('app.helpers.my_helper'); to get the service instance.

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: AppBundleTwigAppExtension
        public: false
        arguments: ['@app_helpers.my_helper']
        tags:
            - { name: twig.extension }

You can read more about this in symfony Service container documentation and Twig extension documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...