我想根据路由参数将 Doctrine 实体注入(inject)到 Controller 操作中,以尝试减少我的 Controller 内疯狂的代码重复量。
例如我有以下路线
product:
path: /product/edit/{productId}
defaults: { _controller: ExampleBundle:Product:edit }
代替我目前的做法
public function editAction($productId)
{
$manager = $this->getDoctrine()->getManager();
$product = $manager->getRepository('ExampleBundle:Product')
->findOneByProductId($productId);
if (!$product) {
$this->addFlash('error', 'Selected product does not exist');
return $this->redirect($this->generateUrl('products'));
}
// ...
}
我希望在其他地方处理这个问题,因为它目前在至少 6 个 Controller 操作中重复出现。所以它会更符合
public function editAction(Product $product)
{
// ...
}
似乎这实际上已经完成了,我能找到的最好的例子是由 SensioFrameworkBundle 完成的 http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
我会使用它,但没有在我们的 Symfony 项目中使用注释,因此需要寻找替代方案。关于如何实现这一点有什么建议吗?
最佳答案
如果您阅读 the docs仔细地,您会了解到参数转换器实际上可以在没有注释的情况下工作:
To detect which converter is run on a parameter the following process is run:
- If an explicit converter choice was made with @ParamConverter(converter="name") the converter with the given name is chosen.
- Otherwise all registered parameter converters are iterated by priority. The supports() method is invoked to check if a param converter can convert the request into the required parameter. If it returns true the param converter is invoked.
换句话说,如果您没有在注释中指定参数转换器,Symfony 将遍历所有已注册的转换器并找到最合适的转换器来处理您的参数(基于类型提示)。
我更喜欢添加注释以便:
- 明确
- 节省一些处理时间
关于php - 根据路由参数将 Doctrine Entity 注入(inject) Symfony Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29570343/