在 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()
]);
}