2017-08-04 26 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

相關問題