如何在 symfony2 中解析非控制器类中的路径 [英] How to resolve a path in a non controller class in symfony2
问题描述
我有一个继承自 AbstractType
的表单构建器类,我需要解析这样的路径:
I have a form builder class which inherits from AbstractType
and I need to resolve a path like this:
$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));
由于该类不是 Controller
的子类,因此我无法访问路由器.有什么想法吗?
Since the class is not a child of Controller
I have no access to the router. Any ideas?
在构建时将路由器传递给类怎么样?
What about passing the router to the class on construction time?
推荐答案
您可以通过构造函数将 router
服务传递给您的表单类型.使用 form.type
标记将您的表单注册为服务并向其注入 router
服务.
You can pass the router
service via constructor to your form type. Register your form as a service with the form.type
tag and inject the router
service to it.
<?php
namespace Vendor\Bundle\AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
class PostType extends AbstractType
{
/**
* @var Router
*/
private $router;
/**
* @param Router
*/
public function __construct(Router $router)
{
$this->router = $router;
}
/**
* @return string
*/
public function getName()
{
return 'post';
}
// ...
}
将其注册为服务:
services:
form.type.post:
class: Vendor\Bundle\AppBundle\Form\Type\PostType
arguments: [ @router ]
tags:
- { name: form.type }
并在您的控制器中像这样使用它:
And use it in your controller like this:
public function addAction(Request $request)
{
$post = new Post();
$form = $this->createForm('post', $post);
// ...
}
由于您使用 form.type
标记将表单类型注册为服务,您可以简单地使用其名称而不是 new PostType()
.您可以在您的类型中以 $this->router
的身份访问 router
服务.
Since you registered your form type as a service with the form.type
tag, you can simply use its name instead of new PostType()
. And you can access the router
service as $this->router
in your type.
这篇关于如何在 symfony2 中解析非控制器类中的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!