ed2*_*209 22 dependency-injection symfony
我不想扩展标准控制器,而是将Twig注入我的一个类中.
控制器:
namespace Project\SomeBundle\Controller;
use Twig_Environment as Environment;
class SomeController
{
private $twig;
public function __construct( Environment $twig )
{
$this->twig = $twig;
}
public function indexAction()
{
return $this->twig->render(
'SomeBundle::template.html.twig', array()
);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在services.yml我有以下内容:
project.controller.some:
class: Project\SomeBundle\Controller\SomeController
arguments: [ @twig ]
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
SomeController :: __ construct()必须是Twig_Environment的一个实例,没有给出
但我正在@twig通过config.我看不出我做错了什么.
编辑:
添加正确的代码 - 这是解决问题的原因:
// in `routing.yml` refer to the service you defined in `services.yml`
project.controller.some
project_website_home:
pattern: /
defaults: { _controller: project.controller.some:index }
Run Code Online (Sandbox Code Playgroud)
首先,让我们看一下服务容器中的可用内容:
? php bin/console debug:container | grep twig
twig Twig_Environment
...
? php bin/console debug:container | grep templa
templating Symfony\Bundle\TwigBundle\TwigEngine
...
Run Code Online (Sandbox Code Playgroud)
现在我们可能会选择TwigEngine类(模板服务)而不是Twig_Enviroment(twig服务)。您可以在下面找到模板服务vendor\symfony\symfony\src\Symfony\Bundle\TwigBundle\TwigEngine.php
...
class TwigEngine extends BaseEngine implements EngineInterface
{
...
Run Code Online (Sandbox Code Playgroud)
在此类中,您将找到两个方法render(..)和renderResponse(...),这意味着您的其余代码在下面的示例中可以正常工作。您还将看到TwigEngine注入了树枝服务(Twig_Enviroment类)以构造其父类BaseEngine。因此,不需要请求树枝服务,并且您请求Twig_Environment的错误将消失。
因此,在您的代码中,您将像这样进行操作:
# app/config/services.yml
services:
project.controller.some:
class: Project\SomeBundle\Controller\SomeController
arguments: ['@templating']
Run Code Online (Sandbox Code Playgroud)
你的班
namespace Project\SomeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;
class SomeController
{
private $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
public function indexAction()
{
return $this->templating->render(
'SomeBundle::template.html.twig',
array(
)
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31378 次 |
| 最近记录: |