Laravel 5 中的 RESTful API 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28692453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RESTful API response in Laravel 5
提问by Robo Robok
I'm building RESTful API with Laravel. My API always returns JSON. What I would like to do, is keeping response logic at one place. Here's how I do it right now in API controller, which is pointed to by Route::controller()
. Funny and ultra-useful example coming:
我正在用 Laravel 构建 RESTful API。我的 API 总是返回 JSON。我想做的是将响应逻辑保持在一个地方。这是我现在在 API 控制器中的做法,它由Route::controller()
. 有趣和超有用的例子来了:
public function getDouble($number) {
try {
if (!is_numeric($number)) {
throw new HttpException(400, 'Invalid number.');
}
$response = $number * 2;
$status = 200;
}
catch (HttpException $exception) {
$response = $exception->getMessage();
$status = $exception->getStatusCode();
}
return response()->json($response, $status);
}
In this example, my API route would be for example /double/13
accessed by GET method. The problem is that I repeat this try ... catch block in each method. I would like my API methods to be like:
在这个例子中,我的 API 路由将/double/13
通过 GET 方法访问。问题是我在每个方法中都重复了这个 try ... catch 块。我希望我的 API 方法是这样的:
public function getDouble($number) {
if (!is_numeric($number)) {
throw new HttpException(400, 'Invalid number.');
}
return $number;
}
And then, catch those exceptions and form JSON in another place. What is the best approach here in terms of good application architecture?
然后,捕获这些异常并在另一个地方形成 JSON。就良好的应用程序架构而言,这里的最佳方法是什么?
回答by ultimate
Response on Exception
异常响应
You could do this by handling the exception in App\Exceptions\Handler
.
您可以通过处理App\Exceptions\Handler
.
You could do it in the render method, likeso :
你可以在渲染方法中做到这一点,就像这样:
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if($e instanceof HttpException) {
return response()->json($e->getMessage(), $e->getStatusCode());
}
return parent::render($request, $e);
}
Success Response
成功响应
There are several ways to do this but I guess Middleware would be the best suited one right.
有几种方法可以做到这一点,但我想中间件将是最合适的一种。
- Create a middleware (say, ApiResponseFormatterMiddleware)
- In your 'App\Http\Kernel', add it to
$routeMiddleware
array. - Apply it to the api routes, response to which you want to parse.
- 创建一个中间件(比如 ApiResponseFormatterMiddleware)
- 在您的“App\Http\Kernel”中,将其添加到
$routeMiddleware
数组中。 - 将其应用于要解析的 api 路由、响应。
You could do something in the lines of :
你可以在以下几行中做一些事情:
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
return response()->json($response->getOriginalContent());
}
Ofcourse, you need to change a bit of logic to parse the content the way you want it, but skeleton remains the same.
当然,您需要更改一些逻辑以按照您想要的方式解析内容,但骨架保持不变。