laravel的http路由檔案有兩個api.php
和web.php
➜ ~ ll /Users/shiwenyuan/test/test_demo/routes
total 32
drwxr-xr-x 6 shiwenyuan staff 192 10 9 12:19 ./
drwxr-xr-x 26 shiwenyuan staff 832 10 9 10:29 ../
-rw-r--r-- 1 shiwenyuan staff 572 10 9 12:19 api.php
-rw-r--r-- 1 shiwenyuan staff 508 10 9 10:28 channels.php
-rw-r--r-- 1 shiwenyuan staff 553 10 9 10:28 console.php
-rw-r--r-- 1 shiwenyuan staff 453 10 9 10:35 web.php
從命名上不難理解`web.php`為web服務的路由(用到了檢視層),`api.php`則是做api服務(只負責返回資料)
直接在app/Http/Controllers/Controller.php
中新增實現,然後因為所有控制器都整合了Controller
,所以就會有他的所有public方法,但是這麼寫個人感覺不夠優雅,與laravel的核心思想背道而馳,所以我就把相關實現放到了Provider
中
建立response服務供應者
php artisan make:provider ResponseMacroServiceProvider
//該命令會在app/Providers目錄下生成ResponseMacroServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ResponseMacroServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}
//初始檔案格式如上
修改實現
<?php
namespace App\Providers;
use Carbon\Carbon;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Response;
use App\Library\Error;
class ResponseMacroServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//error
Response::macro('fail', function ($err_code, $result=null, $msg='') {
if (is_null($result)){
$result = [];
}
if ($msg) {
$err_msg = $msg;
} else {
$err_msg = Error::errMsg($err_code);
}
$response_data = [
'code' => $err_code,
'message' => $err_msg,
'timestamp' => Carbon::now()->timestamp
];
app('log')->error(sprintf('params [%s] response [%s]',
json_encode(request()->all(), JSON_UNESCAPED_UNICODE),
json_encode($response_data, JSON_UNESCAPED_UNICODE)
));
return Response::json($response_data);
});
//正常返回
Response::macro('success', function ($result=null) {
if (is_null($result)){
$result = [];
}
$response_data = [
'code' => 100,
'content' => $result,
'timestamp' => Carbon::now()->timestamp
];
app('log')->debug(sprintf('params [%s] response [%s]',
json_encode(request()->all(), JSON_UNESCAPED_UNICODE),
json_encode($response_data, JSON_UNESCAPED_UNICODE)
));
return Response::json($response_data);
});
}
}
App\Library\Error的實現
<?php
/**
* Created by PhpStorm.
* User: shiwenyuan
* Date: 2019/10/9 13341007105@163.com
* Time: 15:13
*/
namespace App\Library;
class Error
{
public static function errMsg($code)
{
$maps = static::getErrs();
return isset($maps[$code]) ? $maps[$code] : '未知錯誤';
}
public static function getErrs()
{
return [
'500' => '伺服器錯誤',
];
}
}
在全域性服務提供者map中加入自己寫的響應服務提供者
檔案位置config/app.php
測試
增加測試路由
檔案路徑:routes/api.php
Route::get('test_success', 'IndexController@testSuccess');
Route::get('test_fail', 'IndexController@testFail');
增加測試實現
<?php
namespace App\Http\Controllers;
class IndexController extends Controller
{
public function testSuccess()
{
return response()->success(['username'=>'shiwenyuan']);
}
public function testFail()
{
return response()->fail(500);
}
}
最終結果
success
fail
日誌記錄
➜ ~ cat /Users/shiwenyuan/test/test_demo/storage/logs/laravel-2019-10-09.log
[2019-10-09 07:39:02] local.DEBUG: params [{"query":"index"}] response [{"code":100,"content":{"username":"shiwenyuan"},"timestamp":1570606742}]
[2019-10-09 07:39:05] local.ERROR: params [{"query":"index"}] response [{"code":500,"message":"伺服器錯誤","timestamp":1570606745}]
本作品採用《CC 協議》,轉載必須註明作者和本文連結