Php Symfony 2-减少冗余代码的方法

Php Symfony 2-减少冗余代码的方法,php,symfony,Php,Symfony,我正在编写一个简单的symfony2web应用程序。我意识到,我的应用程序中几乎每个控制器都在不同的对象上执行相同的操作。我说的是标准CRUD操作:创建、读取、更新和删除。我将以“删除”操作为例 例如: class CustomerController { /** * @Route("/customer") * @Method("DELETE") */ public function deleteAction(Request $request){ $rep =this->ge

我正在编写一个简单的symfony2web应用程序。我意识到,我的应用程序中几乎每个控制器都在不同的对象上执行相同的操作。我说的是标准CRUD操作:创建、读取、更新和删除。我将以“删除”操作为例

例如:

class CustomerController {
/**
 * @Route("/customer")
 * @Method("DELETE")
 */
public function deleteAction(Request $request){
    $rep =this->getDoctrine()->getManager()->getRepository('AppBundle:Customer');

    $customerId = $request->get('id');
    if ($customerId != null) {
        $rep->delete($customerId);
    } else {
        $rep->deleteAll();
    }
    $response = new Response(null, Response::HTTP_OK);
    return $response;
}
}

class ProductController {
/**
 * @Route("/product")
 * @Method("DELETE")
 */
public function deleteAction(Request $request){
    $rep =this->getDoctrine()->getManager()->getRepository('AppBundle:Product');

    $productId = $request->get('id');
    if ($productId != null) {
        $rep->delete($productId);
    } else {
        $rep->deleteAll();
    }
    $response = new Response(null, Response::HTTP_OK);
    return $response;
}
}

class CompanyController {
/**
 * @Route("/company")
 * @Method("DELETE")
 */
public function deleteAction(Request $request){
    $rep =this->getDoctrine()->getManager()->getRepository('AppBundle:Company');

    $companyId = $request->get('id');
    if ($companyId != null) {
        $rep->delete($companyId);
    } else {
        $rep->deleteAll();
    }
    $response = new Response(null, Response::HTTP_OK);
    return $response;
}
}
等等

唯一真正改变的是实体名称(“客户”、“产品”、“公司”等)

你有没有办法摆脱所有这些冗余,同时保持代码的可读性

我想到的第一件事是使用delete方法逻辑创建一个基类,并将实体名作为参数传递。这样做可以吗?例如:

class CustomerController extends BaseController{
/**
 * @Route("/customer")
 * @Method("DELETE")
 */
public function deleteAction(Request $request){
    parent::deleteAction($request, 'AppBundle:Customer');
}

上述解决方案合法吗?有没有办法进一步简化它?

我会使用一个控制器。使用路由获取实体类名称

/**
 * @Route("/{entityName}/{entityId}")
 * @Route("/{entityName}")
 * @Method("DELETE")
 */
public function deleteAction($entityName, $entityId = null){
    $rep =this->getDoctrine()->getManager()->getRepository('AppBundle:'.$entityName);
    if ($productId != null) {
        $rep->delete($productId);
    } else {
        $rep->deleteAll();
    }
    $response = new Response(null, Response::HTTP_OK);
    return $response;
}
}

根据构建路由的方式,您必须将$entityName字符串转换为entityName,例如:/entity name转换为entityName或/entity转换为entity,然后可以通过ID删除数据库中的任何记录,这在我看来是另一个问题。当然,这一点必须以某种方式加以保护。第一步,你可以建立一些被允许删除的实体的白名单。我对这种方法有混合的感觉。一方面,它大大减少了冗余代码的数量。另一方面,我认为这可能违反“单一责任原则”。这也使得代码更难阅读。无论如何,谢谢你的想法。还有一个问题:您如何命名这样的控制器?