Laravel- custom API returns JSON format

According to our specifications, the server returns the handle http request JSON, it should be in the format:

{
    code: 
    data:  
    msg: 
}

This requires Laravel framework default return value (too casual, the lack of a unified structure to wrap the return value) to do some processing, including the following sections:

Use LaravelResponse Macro mechanism to return directly from the Controller

It requires the following few steps:

1, create a ServiceProvider

php artisan make:provider ResponseMacroServiceProvider
<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Response;

class ResponseMacroServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Response::macro('horesp', function ($code=2000, $data=null, $msg=null) { $content = array( 'code' => $code, 'data' => $data, 'msg' => $msg ); return response()->json($content); }); } public function register() { //  } }

 

2, in the config / app.php file 'providers' list, add the following line

App\Providers\ResponseMacroServiceProvider::class,

 

3, create a HOBaseController, after all Controller inherit this class

php artisan make:controller HOBaseController
<? PHP 
namespace App \ Http \ the Controllers; 
use ; App \ Http \ the Controllers \ the Controller 

class HOBaseController the extends the Controller 
{ 
  called after // This method should only be successfully completed the process of requesting a service interface public function response ($ data = null , $ MSG = null ) { return Response () -> horesp (2000, Data $, $ MSG ); } }

  4, after which the class when the controller returns the result directly, using this approach

return $this->response($user->name);

 

Error value returned by the initiative process to do

The principle is to take the initiative to throw an exception, to deal with all cases need to return an error code and error messages, exception handling mechanism is constructed by the framework of the final return value. 

1, create a class HOException

php artisan make:exception HOException

2, App \ Exception folder, create a file HOError.php, for every wrong, defines a method for external calls.

<?php
namespace App\Exceptions;
use \App\Exceptions\HOException as HOException;

class HOError
{
    public function generalErr()
    {
        throw new HOException('General Error Occurred', 2001);
    }

}

3, in which HOBaseController, add the following code

protected $error;
public function error()
{
    $this->error = new HOError();
    return $this->error;
}

4, in App / Exeption / Handler.php file, overwriting render method

use Illuminate\Support\Facades\Log;
use \App\Exceptions\HOException as HOException;
use Illuminate\Http\Exceptions\HttpResponseException;

public function render($request, Exception $exception)
{
    //对详细的错误信息,进行记录,但是不返回给前端
    Log::debug( parent::render($request, $exception) );
    if ( $exception instanceof HOException ) { $msg = $exception->getMessage(); }else{ $msg = 'Server Bad'; } return response()->horesp( $exception->getCode(), null, $msg); }

 5, where the method Controller, can be to return error codes and error information

return $this->error()->generalErr();

 Validate the situation without going through the process to do

HOFormRequest create a class that inherits FormRequest class, create FormRequest later, went from HOFormRequest class integrated solutions from:. Https://www.jianshu.com/p/658f979abfb7

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Exceptions\HOException as HOException;
use Illuminate\Contracts\Validation\Validator as Validator;

class HOFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ //  ]; } protected function failedValidation(Validator $validator) { $message = $validator->errors()->all(); throw new HOException(implode($message), 3000); } }

 

Guess you like

Origin www.cnblogs.com/zhaoxizhe/p/11308139.html