php - 根据路由参数将 Doctrine Entity 注入(inject) Symfony Controller

标签 php symfony doctrine-orm controller entity

我想根据路由参数将 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/

相关文章:

php - 使用 CSS 缩小 php 背景图片

php - 名称或服务未知 [tcp ://redis:6379]

php - Symfony 2 - 在 Twig 模板中访问层次角色

Symfony2 : How to enable autocompletion for annotations in PHPStorm?

symfony - 在configureDatagridFilters中创建自定义类型字段 - Sonata Admin

symfony - 学说 2 树扩展 : Closure Table

symfony - 预更新未触发

php - 使用 PHP 代码在 MySql 中导入 CSV 文件

php - Symfony2 - 学说获取表创建顺序

PHP 基于一个文本值过滤器查询所有列