繁体   English   中英

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

[英]Symfony 2 - ways to reduce redundant code

我正在编写一个简单的Symfony2 Web应用程序。 我意识到几乎我的应用程序中的每个控制器都执行相同的操作,但是对不同的对象进行操作。 我在谈论标准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字符串转换为例如:/ entity-name转换为EntityName或/ entity转换为Entity

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM