2

在 Controller 中,您可以使用以下内容定义更新操作:

    /**
     * @Route("/product/edit/{id}")
     */
    public function updateAction(Product $product)
    {
     // product is auto select from database by id and inject to controller action.
    }

自动注入非常方便,但是如何将 Doctrine Manager 实例注入到控制器动作中,如果不手动创建 Doctrine Manager 实例会更方便。如下所示:

    /**
     * @Route("/product/edit/{id}")
     */
    public function updateAction(Product $product, ObjectManager $em)
    {
       $product->setName("new name");
       $em->flush();
    }

而不是长编码:

/**
 * @Route("/product/edit/{id}")
 */
public function updateAction($id)
{
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository(Product::class)->find($id);

    if (!$product) {
        throw $this->createNotFoundException(
            'No product found for id '.$id
        );
    }

    $product->setName('New product name!');
    $em->flush();

    return $this->redirectToRoute('app_product_show', [
        'id' => $product->getId()
    ]);
}
4

1 回答 1

2

我还没有尝试过 Symfony4,但是根据官方的 symfony 文档,有基于动作的依赖注入,所以你应该能够通过将服务接口声明为你的动作的参数来使用服务。

https://symfony.com/doc/4.1/controller.html#controller-accessing-services

如果您需要控制器中的服务,只需键入带有其类(或接口)名称的参数即可。Symfony 会自动向您传递您需要的服务:

因此,在您的情况下,它应该如下所示:

/**
  * @Route("/product/edit/{id}")
  */
public function updateAction(Product $product, EntityManagerInterface $em)
{
    $product->setName("new name");
    $em->flush();
}
于 2017-12-06T12:55:46.660 回答