根据路线参数将主义实体注入Symfony控制器 [英] Injecting Doctrine Entity into Symfony controller based on route parameters

查看:56
本文介绍了根据路线参数将主义实体注入Symfony控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于路由参数将Doctrine实体注入到控制器动作中,以减少控制器内部疯狂的代码重复量.

I want to inject Doctrine entities into controller actions based on the route parameters in an attempt to reduce the insane amount of code duplication inside my controllers.

例如,我有以下路线

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个控制器操作中会重复执行此操作.因此,它将更像

I'd like this to be handled else where as it's repeated in at least 6 controller actions currently. So it would be more along the lines of

public function editAction(Product $product)
{
    // ...
}

似乎这实际上是之前完成的,而我能找到的最佳示例是通过SensioFrameworkBundle

It seems this has in fact been done before and the best example I can find is done by the SensioFrameworkBundle http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html

我会用它,但是在我们的Symfony项目中没有使用注解,因此需要研究替代方法.关于如何实现的任何建议?

I'd use this but were not using annotations in our Symfony projects so need to look at alternatives. Any suggestions on how this can be achieved?

推荐答案

如果您阅读

If you read the docs carefully, you'll learn that param converters actually work without annotations:

要检测哪个转换器在参数上运行,请运行以下过程:

To detect which converter is run on a parameter the following process is run:

  • 如果使用@ParamConverter(converter ="name")做出了明确的转换器选择,则会选择具有给定名称的转换器.
  • 否则,所有注册的参数转换器都按优先级进行迭代.调用supports()方法来检查参数转换器是否可以将请求转换为所需的参数.如果返回true,则调用参数转换器.

换句话说,如果您未在注释中指定参数转换器,Symfony将遍历所有已注册的转换器,并找到最合适的转换器来处理您的参数(基于类型提示).

In other words if you don't specify a param converter in an annotation, Symfony will iterate through all registered converters and find the most appropriate one to handle your argument (based on a type hint).

我希望添加注释,以便:

I prefer to put an annotation in order to:

  • 要明确
  • 节省一些处理时间

这篇关于根据路线参数将主义实体注入Symfony控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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