0
如何在控制器中調用構造函數和表單以避免在繼承上下文中複製代碼?控制器中實體繼承的最佳做法
例如:
實體:
class Shape {
…
}
class Circle extends Shape {
…
}
class Rectangle extends Shape {
…
}
控制器:
我需要管理很多,許多子像圓,矩形,菱形,方形...我想只有一個控制器。那麼對於CRUD操作?
現在,它是這樣的:
class ShapeController extends Controller {
/**
* @Route("/shape/index", name="shape_index")
*/
public function indexAction()
{
$shapes = $this->getDoctrine()->getRepository('AppBundle:Shape')->findAll();
return $this->render('shape/index.html.twig', [
'shapes' => $shapes
]);
}
/**
* @Route("/shape/{type}/new", name="shape_new")
*/
public function newAction(Request $request, $type)
{
$formtype = 'AppBundle\Entity\\'.ucfirst($type).'Type';
$class = 'AppBundle\Entity\\'.ucfirst($type);
$shape = new $class();
$form = $this->createForm(new $formtype(), $shape);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($shape);
$em->flush();
return $this->redirect($this->generateUrl(
'shape_index'
));
}
return $this->render('shape/new.html.twig', [
'form' => $form->createView(),
'shape' => $shape
]);
}
而那些工廠被用作服務? –
是的,你需要在你的'services.yml'文件中註冊它們。然後在控制器中用'$ this-> get('service_name')' –
在控制器中使用它們。好吧,我很好,但在我的情況下,我如何傳遞參數「type」? –