duandi8544 2015-02-24 09:44
浏览 143
已采纳

Laravel 5中的RESTful API响应

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:

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:

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?

  • 写回答

1条回答 默认 最新

  • doubo4824 2015-02-24 18:59
    关注

    Response on Exception

    You could do this by handling the exception in 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.

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格