模拟控制器
问题描述:
我在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。似乎更合乎逻辑,并且可以在其他时刻使用它。解决方案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)
}