如何将请求堆栈注入到枝条扩展中

时间:2015-02-23 11:27:48

标签: php symfony request

我试图创建一个扩展来呈现分页。它需要请求和路由器才能创建URL,所以我这样做了:

services.yml:

app.twig_extension:
    class: MyBundle\Twig\MyExtension
    public: false
    calls:
      - [setRequest, [@request_stack]]
      - [setRouter, [@router]]
    tags:
        - { name: twig.extension }

然后在我的扩展名中:

private $router;

private $request;

public function setRouter( UrlGeneratorInterface $router )
{
    $this->router = $router;
}

public function setRequest(RequestStack $requestStack)
{
    $this->request = $requestStack->getCurrentRequest();
}

...

public function renderPaginator(\Twig_Environment $twig, $paginator, array $options = array())
{

    if ( 1 == $paginator->getNumPages() )
    {
        return false;
    }
    var_dump($this->request);
    die();

原来var_dump打印为null。虽然如果我在setRequest方法中执行var_dump,它实际上会打印一个Request对象。 任何的想法?谢谢!

2 个答案:

答案 0 :(得分:4)

构建树枝扩展时,堆栈中没有请求,它是空的。

您应该延迟从堆栈检索请求到renderPaginator()方法。

服务定义:

app.twig_extension:
    class: MyBundle\Twig\MyExtension
    public: false
    arguments: [@request_stack, @router]
    tags:
        - { name: twig.extension }

服务:

public function __construct(RequestStackInterface $requestStack, RouterInterface $router)
{
    $this->requestStack = $requestStack;
    $this->router = $router;
}

public function renderPaginator(\Twig_Environment $twig, $paginator, array $options = array())
{

    if ( 1 == $paginator->getNumPages() )
    {
        return false;
    }
    var_dump($this->requestStack->getCurrentRequest());
    die();
}

答案 1 :(得分:0)

我也在symfony谷歌小组问过这个问题,问题解决了...我有另一个services.yml导致冲突。谢谢大家的时间 https://groups.google.com/forum/?hl=en#!topic/symfony2/pRJTYeAYmHE