美文网首页
laravel 返回值下划线转驼峰

laravel 返回值下划线转驼峰

作者: swoft_ | 来源:发表于2019-09-25 19:34 被阅读0次

思路:写个middleware把返回值递归转一下

class ResponseTransFormMiddleware
{
    //下划线转驼峰
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        return $this->changeHump(json_decode($response->original,true));
    }


    //转换驼峰(只转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注册

$app->routeMiddleware(['responseTransForm' => App\Http\Middleware\ResponseTransFormMiddleware::class,]); //下划线转驼峰

所有的api加一个前缀

$router->group(['prefix' => 'api','middleware'=>'responseTransForm'], function () use ($router) {...});

相关文章

网友评论

      本文标题:laravel 返回值下划线转驼峰

      本文链接:https://www.haomeiwen.com/subject/dmaxyctx.html