2017-06-06 98 views
2

我在symfony項目工作中的請求,我有我的控制器配備了兩個功能:具有良好的請求參數模擬控制器

function1Action ($request Request, $product) { 
    $quantity = $request->request->get('quantity') 
    //dothingshere 
} 
function2Action($product, $value) { 
    $em = $this->getDoctrine()->getManager(); 
    $pattern = $em->getRepository('repo')->find($value) 
    //return an array ['quantity'=>x] 
    $this->function1Action($pattern, $product) 
} 

通常是用戶調用函數1(職位要求)。所以這裏一切都很好。我的問題是,有時,功能2會被調用,當它是我需要調用函數1,但我沒有一個適當的請求,我想送$pattern

所以我發現3溶液

方案1: 創建function1bis誰做同樣的事情,但功能1取一個數組作爲參數

解決方法2:在我的第一功能啓動一個空值

function1 ($request Request, $product, $patt=null) { 
    if(!$patt){ 
     $quantity = $request->request->get('quantity') 
    } 
    else { 
     $quantity = $patt['quantity'] 
    } 
    //dothingshere 
} 
function2($product, $value) { 
    $em = $this->getDoctrine()->getManager(); 
    $pattern = $em->getRepository('repo')->find($value) 
    //return an array ['quantity'=>x] 
    $this->function1Action(null, $product, $pattern); 
} 

解決方案3: 在function2中創建一個對象請求。

我試圖做的解決方案3,但我怎麼也找不到,我想知道的心願一個是「best'and如果解決方案3是不壞的編程

回答

1

我終於做到了選項1。似乎更合乎邏輯,並且可以在其他時刻使用它。解決方案2似乎是有風險的,因爲null參數可能會在其他地方引發問題,而解決方案3將需要更多的資源,因爲我必須在我的函數2中執行foreach。所以我的解決方案如下所示:

function1Action ($request Request, $product) { 
    $quantity = $request->request->get('quantity') 
    //dothingshere 
} 
function1bis($pattern, $product) { 
    $quantity = $pattern['quantity'] 
    //dothingshere 
} 

function2Action($product, $value) { 
    $em = $this->getDoctrine()->getManager(); 
    $pattern = $em->getRepository('repo')->find($value) 
    //return an array ['quantity'=>x] 
    $this->function1bis($pattern, $product) 
}