从服务生成链接

时间:2012-04-07 18:48:32

标签: url symfony service

如何从服务生成链接?我在我的服务中注入了“router”,但生成的链接是/view/42而不是/app_dev.php/view/42。我该如何解决这个问题?

我的代码是这样的:

services.yml

services:
    myservice:
        class: My\MyBundle\MyService
        arguments: [ @router ]

MyService.php

<?php

namespace My\MyBundle;

class MyService {

    public function __construct($router) {

        // of course, the die is an example
        die($router->generate('BackoffUserBundle.Profile.edit'));
    }
}

3 个答案:

答案 0 :(得分:31)

所以:你需要两件事。

首先,您必须依赖@router(以获取generate())。

其次,您必须将服务范围设置为“请求”(我已经错过了)。 http://symfony.com/doc/current/cookbook/service_container/scopes.html

您的services.yml变为:

services:
    myservice:
        class: My\MyBundle\MyService
        arguments: [ @router ]
        scope: request

现在您可以使用@router服务的生成器功能了!


关于Symfony 3.x的重要说明:正如doc所说,

  

本文中解释的“容器范围”概念已经存在   在Symfony 2.8中已弃用,它将在Symfony 3.0中删除。

     

使用request_stack服务(在Symfony 2.4中引入)代替   request服务/范围,并使用shared设置(在   Symfony 2.8)而不是prototype范围(阅读更多关于共享的内容)   服务)。

答案 1 :(得分:5)

对于 Symfony 4.x ,按照此链接Generating URLs in Services

中的说明进行操作要容易得多。

您只需在服务中注入UrlGeneratorInterface,然后调用generate('route_name')即可检索链接。

// src/Service/SomeService.php
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SomeService
{
    private $router;

    public function __construct(UrlGeneratorInterface $router)
    {
        $this->router = $router;
    }
    public function someMethod()
    {
        // ...

        // generate a URL with no route arguments
        $signUpPage = $this->router->generate('sign_up');
    }

    // ...
}

答案 2 :(得分:4)

我有一个similar issue,但是使用了Symfony 3。 虽然在上一个答案中没有提及,但要弄清楚如何使用request_stack来实现与scope: request相同的事情有点棘手。

在这个问题的案例中,它看起来像这样:

services.yml config

services:
    myservice:
        class: My\MyBundle\MyService
        arguments:
            - '@request_stack'
            - '@router'

MyService Class

<?php

    namespace My\MyBundle;

    use Symfony\Component\Routing\RequestContext;

    class MyService {

        private $requestStack;
        private $router;

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

        public doThing() {
            $context = new RequestContext();
            $context->fromRequest($this->requestStack->getCurrentRequest());
            $this->router->setContext($context);
            // of course, the die is an example
            die($this->router->generate('BackoffUserBundle.Profile.edit'));
        }
    }

注意:在构造函数中访问RequestStack是advised against,因为它可能会在内核处理请求之前尝试访问它。因此,当尝试从RequestStack获取请求对象时,它可能返回null。