inject a service in a twig extesion.


I would advise creating a general service and injecting it to the Twig extension. The extension would act just as a wrapper to the service.
namespace Acme\Bundle\DemoBundle\...;
class MyService
{
    public function myFunc($foo, $bar)
    {
        // some code...
    }

    // additional methods...
}

namespace Acme\Bundle\DemoBundle\Twig\Extension;
class MyTwigExtension extends \Twig_Extension
{
    protected $service;

    public function __construct(MyService $service)
    {
        $this->service = $service;
    }

    public function getFunctions()
    {
        return array(
            'myTwigFunction' => new \Twig_Function_Method($this->service, 'myFunc'),
            'mySecondFunc'   => new \Twig_Function_Method($this->service, 'mySecondFunc'),
        );
    }
}
不过我并不确定这个 twig_function_method 返回的数组到底怎么用。

评论

热门博文