Url 从服务生成链接
如何从服务生成链接?我在我的服务中注入了“路由器”,但是生成的链接是Url 从服务生成链接,url,symfony,service,Url,Symfony,Service,如何从服务生成链接?我在我的服务中注入了“路由器”,但是生成的链接是/view/42,而不是/app\u dev.php/view/42。我怎样才能解决这个问题 我的代码是这样的: services.yml services: myservice: class: My\MyBundle\MyService arguments: [ @router ] MyService.php <?php namespace My\MyBundle; clas
/view/42
,而不是/app\u 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'));
}
}
所以:你需要两样东西 首先,您必须依赖于@router(才能获得generate()) 其次,您必须将服务范围设置为“请求”(我错过了)。 您的
服务.yml
变为:
services:
myservice:
class: My\MyBundle\MyService
arguments: [ @router ]
scope: request
现在您可以使用@router服务的生成器功能了
关于Symfony 3.x的重要注意事项:正如 本文中解释的“容器范围”概念 在Symfony 2.8中已弃用,将在Symfony 3.0中删除 使用
request_stack
服务(在Symfony 2.4中引入)代替
请求
服务/范围并使用共享
设置(在中介绍
Symfony 2.8)而不是原型
范围(阅读更多关于共享
服务)
我有一个,但使用Symfony 3。
虽然在上一个回答中没有提到,但要弄清楚如何使用request\u stack
来实现与scope:request
相同的功能有点棘手
在这个问题中,它看起来是这样的:
services.yml配置文件
services:
myservice:
class: My\MyBundle\MyService
arguments:
- '@request_stack'
- '@router'
还有MyService类
<?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'));
}
}
对于Symfony 4.x,按照此链接中的说明操作要容易得多
您只需在服务中插入UrlGeneratorInterface
,然后调用generate('route_name')
,即可检索链接
//src/Service/SomeService.php
使用Symfony\Component\Routing\Generator\UrlGeneratorInterface;
类服务
{
私人路由器;
公共函数构造(UrlGeneratorInterface$router)
{
$this->router=$router;
}
公共函数方法()
{
// ...
//生成不带路由参数的URL
$signUpPage=$this->router->generate('signup');
}
// ...
}
如果您通过http://test/app_dev.php
,链接将与app_dev.php一起提供。对于http://test
他们将没有app_dev.php…@kuba:我已经编辑了我的问题。@meze:我访问了app_dev.php页面,但是链接在url中没有这部分内容。这就是问题所在。如果你在模板中尝试,URL是否生成正确?我不明白。这有什么帮助?作用域与app_dev.php
无关。如果使用路由器时请求不可用,路由器的上下文(getContext())将不会使用请求信息(例如主机),并且不会完全生成路径。设置作用域确保在创建我的服务时请求将处于活动状态注意,还有第二个特定问题:我在bundle启动时加载了我的服务,因此,请求尚未加载。按照您的建议执行操作时,我遇到此错误:ScopeCrossingInjectionException:Scope Crossing Injection检测到:定义“myservice”引用了属于另一个作用域层次结构的服务“router.default”。此服务可能不一致可用。通常,将定义“myservice”移动到作用域“container”或将“router”声明为“container”的子作用域更安全。如果您可以确保另一个作用域始终处于活动状态,则可以将引用设置为strict=false以消除此错误。
@Toskan:在您的服务中,请添加:使用Symfony\Component\Routing\RouterInterface代码>在服务构造函数中添加RouterInterface$variableName,
,并在末尾从service.yml
中删除scope=router
。旁注:如果您想在其他服务中使用myservice
作为依赖项,可能必须在末尾用=
传递它(如参数:[@myservice=]
),yml语法设置为strict=false
。否则可能会抛出scopewideInjectionException
。但是,将服务定义为Twig的全局服务时,=
-语法不起作用。