Php 使用die()创建的请求也会终止请求调用方
我不知道雇佣条件是否合适 我制作了一个API,其中答案由die()函数发送,以避免一些更无用的计算和/或函数调用 例如:Php 使用die()创建的请求也会终止请求调用方,php,laravel,Php,Laravel,我不知道雇佣条件是否合适 我制作了一个API,其中答案由die()函数发送,以避免一些更无用的计算和/或函数调用 例如: if (isset($authorize->refusalReason)) { die ($this->api_return(true, [ 'resultCode' => $authorize->resultCode, 'reason' => $authorize->refusalReason
if (isset($authorize->refusalReason)) {
die ($this->api_return(true, [
'resultCode' => $authorize->resultCode,
'reason' => $authorize->refusalReason
]
));
}
//api_返回方法:
protected function api_return($error, $params = []) {
$time = (new DateTime())->format('Y-m-d H:i:s');
$params = (array) $params;
$params = ['error' => $error, 'date_time' => $time] + $params;
return (Response::json($params)->sendHeaders()->getContent());
}
但我的网站是基于此API的,因此我创建了一个函数来创建请求
,并根据其URI、方法、参数和标题返回其内容:
protected function get_route_contents($uri, $type, $params = [], $headers = []) {
$request = Request::create($uri, $type, $params);
if (Auth::user()->check()) {
$request->headers->set('S-token', Auth::user()->get()->Key);
}
foreach ($headers as $key => $header) {
$request->headers->set($key, $header);
}
// things to merge the Inputs into the new request.
$originalInput = Request::input();
Request::replace($request->input());
$response = Route::dispatch($request);
Request::replace($originalInput);
$response = json_decode($response->getContent());
// This header cancels the one there is in api_return. sendHeaders() makes Content-Type: application/json
header('Content-Type: text/html');
return $response;
}
但是现在,当我试图调用一个API函数时,API中的请求会消失,但我当前的请求也会消失
public function postCard($token) {
$auth = $this->get_route_contents("/api/v2/booking/payment/card/authorize/$token", 'POST', Input::all());
// the code below is not executed since the API request uses die()
if ($auth->error === false) {
return Redirect::route('appts')->with(['success' => trans('messages.booked_ok')]);
}
return Redirect::back()->with(['error' => $auth->reason]);
}
你知道我能不能处理得比这更好吗?有没有关于如何将代码转换为
我知道我可以使用退货,但我总是想知道是否还有其他解决方案。我的意思是,我想做得更好,所以如果我确实知道做我想要的事情的唯一方法是使用返回,我就不会问这个问题。因此,您似乎是通过代码调用API端点,好像它来自浏览器(客户端),我假设您的路由:dispatch没有发出任何外部请求(如curl等) 现在可以有多种方法来处理此问题:
get\u route\u contents
将处理所有请求,那么您需要从端点移除骰子,只需让它们返回数据(而不是回显)。您的这个“处理程序”将负责响应echo
我希望有另一种解决方案,实际上我不想特别在错误处理中使用返回,如果一个函数(由另一个函数调用,本身从方法调用)返回一个数组,那么我如何知道它是我的API答案(如果错误)还是数组(如果成功)?您认为如果在新线程中执行
get\u route\u contents
会解决问题吗?事实上,它不需要新的线程。对于这个请求,只需要一个新的httpd进程。我会查一查这是否可行。嗯,我用了退货。谢谢你的建议