简体   繁体   中英

How call method from service container in config in Symfony?

I have some variables in twig-templates, so think use global scope for it.

config.yml
twig:
 globals:
  varA: "@wf.autoload.getA"
  varB: "@wf.autoload.getB"

In service yml I have:

services.yml
 wf.autoload:
  class: Scope\WfBundle\WfAutoloadService
  arguments: ["@doctrine.orm.entity_manager"]

WfAutoloadService class have public function for getting variables

    class WfAutloadService {
    ...
    public function getA(){
    return ...;
    }

    public function getB(){
    return ...
    }
    ...
    }

My idea doesn't work. Method of @=service(wf.autoload).getA() also doesn't work.

Is it possible? Or it bad idea and bad practice?

Thanks

If getA() and getB() returns object, you can use a factory when configuring your service:

services:
    wf.autoload:
        class: Scope\WfBundle\WfAutoloadService
        arguments: ["@doctrine.orm.entity_manager"]
    wf.autoload.getA:
        class:   A
        factory: ["@wf.autoload", getA]

And set the global twig:

twig:
 globals:
  varA: "@wf.autoload.getA"

I you want to use this functions in many twig templates you can create a twig extension

For example :

class MyExtensions extends \Twig_Extension
{
    public function getFunctions()
    {
            return array(
                'getA' => new \Twig_Function_Method($this, 'getA', array('is_safe' => array('html')))
            );
    }

    public function getA() // you can if you want pass parameters
    {
       //your code

       return ...
    }
}

Declare it as service :

myextensions.twig_extension:
      class: Project\YourBundle\Twig\MyExtensions
      public: false
      tags:
          - { name: twig.extension }

And call it in yours twig template :

{{ getA() }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM