【Laravel】前后端不同命名方式的自动转换
后端PHP习惯用驼峰命名,如variableName;前端因为希望遵循restful api规范,采用了下划线命名,如variable_name。于是就有了前后端的参数名自动转换的需求。
处理方式是在Laravel中增加Middleware,代码如下
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\ParameterBag;
/**
* Class ApiCaseConverter
*
* 1. 将前端请求参数的下划线命名转换为后端的驼峰命名
* 2. 将后端响应参数的驼峰命名转换为前端的下划线命名
*
* @package App\Http\Middleware
*/
class ApiCaseConverter
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$this->convertRequestNameCase($request);
/** @var Response $response */
$response = $next($request);
$this->convertResponseNameCase($response);
return $response;
}
/**
* 转换请求参数中的下划线命名转换为驼峰命名
*
* @param Request $request
*/
private function convertRequestNameCase($request)
{
$this->convertParameterNameCase($request->request);
$this->convertParameterNameCase($request->query);
$this->convertParameterNameCase($request->files);
$this->convertParameterNameCase($request->cookies);
}
/**
* 将参数名称的下划线命名转换为驼峰命名
*
* @param ParameterBag $parameterBag
*/
private function convertParameterNameCase($parameterBag)
{
$parameters = $parameterBag->all();
$newParameters = [];
foreach ($parameters as $key => $value) {
$newParameters[Str::camel($key)] = $value;
}
$parameterBag->replace($newParameters);
}
/**
* 将响应中的参数命名从驼峰命名转换为下划线命名
*
* @param Response $response
*/
private function convertResponseNameCase($response)
{
$content = $response->getContent();
$json = json_decode($content, true);
if (is_array($json)) {
$json = $this->recursiveConvertNameCaseToSnake($json);
$response->setContent(json_encode($json));
}
}
/**
* 循环迭代将数组键值转换为下划线格式
*
* @param array $arr
* @return array
*/
private function recursiveConvertNameCaseToSnake($arr)
{
if (!is_array($arr)) {
return $arr;
}
$outArr = [];
foreach ($arr as $key => $value) {
$outArr[Str::snake($key)] = $this->recursiveConvertNameCaseToSnake($value);
}
return $outArr;
}
}
在App\Http\Kernal中增加以下代码即可
protected $middlewareGroups = [
'api' => [
ApiCaseConverter::class,
],
];
还没有人抢沙发呢~