从服务生成链接 [英] Generate a link from a service

查看:47
本文介绍了从服务生成链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I generate a link from a service? I've injected "router" inside my service, however generated links are /view/42 instead of /app_dev.php/view/42. How can I solve this?

我的代码是这样的:

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'));
    }
}

推荐答案

所以:你需要做两件事.

So : you will need two things.

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

First of all, you will have to have a dependency on @router (to get generate()).

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

Secondly, you must set the scope of your service to "request" (I've missed that). http://symfony.com/doc/current/cookbook/service_container/scopes.html

你的 services.yml 变成:

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

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

Now you can use the @router service's generator function !

关于 Symfony 3.x 的重要说明:作为 doc 说,

本文中解释的容器作用域"概念已经在 Symfony 2.8 中弃用,它将在 Symfony 3.0 中删除.

The "container scopes" concept explained in this article has been deprecated in Symfony 2.8 and it will be removed in Symfony 3.0.

使用 request_stack 服务(在 Symfony 2.4 中引入)而不是request 服务/范围并使用 shared 设置(在Symfony 2.8) 而不是 prototype 作用域(阅读更多关于 shared服务).

Use the request_stack service (introduced in Symfony 2.4) instead of the request service/scope and use the shared setting (introduced in Symfony 2.8) instead of the prototype scope (read more about shared services).

这篇关于从服务生成链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆