2017-08-04 54 views
2

我有自定义服务,我想在树枝模板中使用它。 在Symfony的< 3我可以这样做:如何在自定义服务中获取Tempating或Container?

use Symfony\Component\DependencyInjection\Container; 
//... 
public function __construct(Container $container) 
{ 
    $this->container = $container; 
} 

public function getView() 
{ 
    $this->container->get('templating')->render('default/view.html.twig'); 
} 

但在Symfony的3.3我有错误:

Cannot autowire service "AppBundle\Service\ViewService": argument "$container" of method "__construct()" references class "Symfony\Component\DependencyInjection\Container" but no such service exists. Try changing the type-hint to one of its parents: interface "Psr\Container\ContainerInterface", or interface "Symfony\Component\DependencyInjection\ContainerInterface".

回答

0

这是not good idea to inject whole container。更好的是注入单一的依赖关系:

use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; 

class MyService 
{ 
    private $templating; 
    public function __construct(EngineInterface $templating) 
    { 
     $this->templating = $templating; 
    } 

    public function getView() 
    { 
     $this->templating->render('default/view.html.twig'); 
    }  
} 
+0

谢谢,但你怎么知道什么接口使用?我在哪里可以检查它?如果我运行“bin/console debug:container”,那么我有:'templating.engine.twig'的模板别名。那么为什么和如何EngineInterface? – roggy

+0

使用'bin/console debug:container templating'的@roggy会给你[提示自动装配类型](https://i.stack.imgur.com/7fkeN.png)。 – jkucharovic

相关问题