控制器

时间:2015-09-08 12:44:06

标签: symfony

如何在控制器中调用构造函数和表单以避免在继承上下文中重复代码?

例如:

实体:

class Shape {
…
}

class Circle extends Shape {
…
}

class Rectangle extends Shape {
…
}

控制器:

我需要管理很多很多子类,比如Circle,Rectangle,Rhombus,Square ......我想要只有一个控制器。那么对于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
    ]);
}

1 个答案:

答案 0 :(得分:1)

最好使用工厂。 ShapeFactory->createFromType($type)ShapeTypeFactory->createFromType($type)

然后,您只需要在控制器中使用这些工厂,并让工厂需要具有Shape / ShapeType实例的责任。