【发布时间】:2014-11-28 23:45:12
【问题描述】:
我有这段代码,我想问哪种方法是停止代码执行的最佳方法,如果有任何失败,直接通过响应。看看这个:
public function guardarPaso6Action(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$response['success'] = false;
$status = null;
if ($request->isXmlHttpRequest()) {
$productoSolicitud = $session->get('productoSolicitudId');
$productoSolicitudEntity = $em->getRepository("AppBundle:ProductoSolicitud")->find($productoSolicitud);
if (! $productoSolicitud) {
$status = 400;
$response['error'] = $this->get('translator')->trans('mensajes.msgElementoNoEncontrado', array('%pronombre%' => 'la','%elemento%' => 'solicitud de producto'), 'AppBundle');
}
$fabricanteEntity = new Entity\FabricanteDistribuidor();
$fabricanteForm = $this->createForm(new Form\FabricanteForm(), $fabricanteEntity);
$fabricanteForm->handleRequest($request);
if ($fabricanteForm->isValid()) {
try {
$em->persist($fabricanteEntity);
$em->flush();
$session->set('fabricanteEntityId', $fabricanteEntity->getId());
} catch (\Exception $ex) {
$status = 400;
$response['error'] = $ex->getMessage();
}
// Some code goes here
$dataResponse['paises'] = $nombresPaises;
$response['entities'] = $dataResponse;
$response['success'] = true;
} else {
$status = 400;
$response['error'] = $this->getFormErrors($fabricanteForm);
}
}
return new JsonResponse($response, $status ?: 200);
}
在这种情况下:
- 如果
!$productoSolicitud应该停止代码执行并通过JsonResponse - 如果有任何
catch (\Exception $ex)应该停止代码执行并通过JsonResponse
你有什么大主意吗?只需在出错时停止代码执行并通过return 语句。我如何做到这一点?我不确定使用exit 或break 是否可以完成这项工作,但我仍然有疑问,有什么建议吗?
【问题讨论】:
标签: php algorithm symfony logic php-5.5