思路:寫個(gè)middleware把返回值遞歸轉(zhuǎn)一下
class ResponseTransFormMiddleware
{
//下劃線轉(zhuǎn)駝峰
public function handle($request, Closure $next)
{
$response = $next($request);
return $this->changeHump(json_decode($response->original,true));
}
//轉(zhuǎn)換駝峰(只轉(zhuǎn)key)
public function changeHump($params)
{
if (is_array($params)) {
foreach ($params as $key=>$value){
unset($params[$key]);
$params[$this->convertUnderline($key)] = is_array($value)?$this->changeHump($value):$value;
}
}
return $params;
}
public function convertUnderline($str)
{
return preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {return strtoupper($matches[2]);}, $str);
}
}
middleware注冊(cè)
$app->routeMiddleware(['responseTransForm' => App\Http\Middleware\ResponseTransFormMiddleware::class,]); //下劃線轉(zhuǎn)駝峰
所有的api加一個(gè)前綴
$router->group(['prefix' => 'api','middleware'=>'responseTransForm'], function () use ($router) {...});