0
私はシンプルなSymfony2 Webアプリケーションを作成しています。アプリケーションのほぼすべてのコントローラーが同じ操作を行いますが、別のオブジェクトで動作することに気付きました。私はCRUDの標準的な操作、つまり作成、読み込み、更新、削除について話しています。Symfony 2 - 冗長コードを減らす方法
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;
}
}
のように...
本当にエンティティ名が変更さ唯一のもの(「顧客」、「製品:私は例
例として「削除」操作を使用します"、" Company "など)。
このすべての冗長性を取り除き、同時にコードを読み取り可能にする方法はありますか?
私の頭に浮かぶのは、deleteメソッドのロジックで基本クラスを作成し、エンティティ名をパラメータとして渡すことです。それはいいですか?例:
class CustomerController extends BaseController{
/**
* @Route("/customer")
* @Method("DELETE")
*/
public function deleteAction(Request $request){
parent::deleteAction($request, 'AppBundle:Customer');
}
上記の解決策はありますか?それをさらに単純化する方法はありますか?
へ/エンティティ名エンティティ名または/エンティティ:
あなたのルートを構築する方法に応じて、インスタンスのための$エンティティネームの文字列を変換する必要がありますそれを実行する権限、IDでデータベース内のレコードを削除することができる –
それは私の視点から見た別の問題です。コースターの中では、このenpointはどうにかして保護されなければなりません。最初のステップで、許可されたエンティティのホワイトリストを作成して削除することができます。 – Carlos
私はこのアプローチに向かって気持ちが混ざっています。一方では、冗長コードの量を大幅に削減します。一方、私はそれが「単一責任の原則」に違反するかもしれないと思う。また、コードを読みにくくします。とにかくこの考えに感謝します。もう1つ質問:あなたはそのようなコントローラーの名前をどのようにしますか? –