Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...