Laravel & Lumen RESTFul API 扩展包:Dingo API(二) -- 创建 API Endpoint(路由)

WBOY
Release: 2016-06-23 13:11:39
Original
985 people have browsed it

Endpoint 就是路由的另一种术语,当我们讨论API时,很多人习惯将访问的路由看作Endpoint。

1、 版本号

为了避免和主应用的路由混在一起,Dingo API使用了自己的路由器,正因如此我们首先需要获取API路由器实例来创建Endpoint:

$api = app('Dingo\Api\Routing\Router');
Copy after login

接下来需要定义版本号,从而可以为多版本API创建同样的Endpoint以便后续回滚:

$api->version('v1', function ($api) {});
Copy after login

如果你想要某个组响应多个版本的API可以传递多版本数组:

$api->version(['v1', 'v2'], function ($api) {});
Copy after login

这里的版本号可以看作和框架的标准路由分组一样传递数组属性作为第二个参数:

$api->version('v1', ['middleware' => 'foo'], function ($api) {});
Copy after login

还可以嵌套普通版分组以便后续实现更复杂的自定义Endpoint:

$api->version('v1', function ($api) {    $api->group(['middleware' => 'foo'], function ($api) {        // Endpoints registered here will have the "foo" middleware applied.    });});
Copy after login

2、创建Endpoint

有了版本号之后就可以开始使用 $api创建Endpoint了:

$api->version('v1', function ($api) {    $api->get('users/{id}', 'App\Api\Controllers\UserController@show');});
Copy after login

因为Endpoint以版本号进行分组,所以你可以使用同样的URI为同一Endpoint创建不同的响应:

$api->version('v1', function ($api) {    $api->get('users/{id}', 'App\Api\V1\Controllers\UserController@show');});$api->version('v2', function ($api) {    $api->get('users/{id}', 'App\Api\V2\Controllers\UserController@show');});
Copy after login

还可以使用各自的方法注册资源和控制器。

注意:与Laravel不同,这里必须指定控制器的完整命名空间。

命名路由并生成URL

命名路由可以帮助我们轻松生成对应URL。你可以像在Laravel中一样命名路由:

$api->get('users/{id}', ['as' => 'users.index', 'uses' => 'Api\V1\UserController@show']);
Copy after login

然后你可以生成URL到这个命名路由:

app('Dingo\Api\Routing\UrlGenerator')->version('v1')->route('users.index');
Copy after login

必须提供一个版本号以便URL可以基于该版本号生成,同时,你可以在不同版本号中使用同一个命名路由。

3、在控制台查看路由

如果你使用的是Laravel 5.1,可以使用Artisan命令查看注册路由:

$ php artisan api:routes
Copy after login

该命令和Laravel中的 route:list命令一样。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!