generateUrl 外部控制器 [英] generateUrl outside controller
问题描述
是否可以在控制器之外使用 generateUrl() 方法?
Is there a possibility to use generateUrl() method outside of controllers?
我尝试在带有 $this->get('router')
的自定义存储库类中使用它,但没有成功.
I tried to use it in a custom repository class with $this->get('router')
, but it didn't work.
更新
我在这里找到了一个临时解决方案:
I've found a temporary solution here:
http://www.phamviet.net/2012/12/09/symfony-2-inject-service-as-dependency-in-to-repository/
我将整个服务容器注入到我的存储库中,尽管不推荐"这样做.
I injected the whole service container into my repository, although it's "not recommended".
但它现在有效.
update2
注入路由器而不是整个容器可能是一个更好的主意:)
Injecting router instead of the whole container is probably a better idea :)
推荐答案
不要将容器注入您的存储库...真的,不要!
Don't inject the container into your repository... Really, don't !
如果我是你,我会创建一个服务并将路由器注入其中.在此服务中,我将创建一个方法,该方法使用存储库并使用路由器添加所需的代码.
If I were you, I would create a service and injects the router in it. In this service, I would create a method, that uses the repository and adds the needed code using the router.
对于其他开发人员来说,这样更简洁,更易于使用/理解.
That's way less dirty and easy to use/understand for another developer.
这篇关于generateUrl 外部控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!