分享一个增加 Laravel View 功能的扩展包:wuwx/Laravel-plus-view
首先上 github 地址:https://github.com/wuwx/laravel-plus-view
1. 背景介绍
我们通常会有这样的需求,同一个控制器的同一个动作,可能会需要有不同的数据格式展现需求,例如同样一个请求用户信息的地址:http://localhost:8000/users
有时候我们希望他对外使用 HTML 格式输出,有时候我们希望他使用 json 格式输出,我们可能会采用这样的做法:
public function index(Request $request)
{
....
if ($request->format() == 'json') {
return Response::json($users);
} else {
return view('users.index');
}
....
}
默认情况下,Laravel 会去寻找 view 下的 users/index.blade.php
文件去渲染
不过我总感觉这种把 format 暴力写入控制器的做法有点不太美,如果你想临时增加一种视图输出格式,就需要去修改(污染)控制器,一直在想应该有 一种更美的做法来解决这个事情。
2. 扩展包介绍
laravel-plus-view 这个扩展包的做法是不在控制器里显式指定渲染格式,而是通过匹配 views 下的文件自动匹配,如果你使用 laravel-plus-view 的话,控制器的写法就是这样:
public function index()
{
....
return view('users.index');
....
}
乍一看,好像控制器啥也没做,控制器确实啥也没做,但是!如果你想显示的是 html 格式,他就会去渲染 users/index.html.blade.php
,如果你想显示的是 json 格式,他就会去渲染 users/index.json.blade.php
文件,同样,如果你想显示的是 xml 格式,他就会去渲染 users/index.xml.blade.php
了。
对控制器没有任何侵入性,假如你不需要这样的特性也没关系,你还是使用原有的写法,保留 users/index.blade.php
同样是可以正常使用的,不需要更改你原有的视图路径。
3. 安装方法
composer require wuwx/laravel-plus-view
'providers' => [
Wuwx\LaravelPlusView\LaravelPlusViewServiceProvider::class,
],
4. 请求测试
使用 curl 请求可以模拟不同的 Accept 请求不同的格式
请求默认的 html 格式
curl http://localhost:8000/users
请求一个 json 格式
curl http://localhost:8000/users -H "Accept: application/json"
同时还实现了一个 format 参数,用于直接在 url 里指定类型
curl http://localhost:8000/users?format=json
最后,欢迎大家使用,让我们一起来强大 Laravel 社区 :)
推荐文章: