第三节:dingo/API 最新版 V2.0 之 Creating API Endpoints (连载)

对于这篇文章的标题,其实,直译就是建立api端点。可是,真的很难懂,我仍是写为API路由吧。每篇,文章,我都会所有去进行实践操做,力求写一个好点的教程。php

本文英文地址——>https://github.com/dingo/api/wiki/Creating-API-Endpointshtml

An endpoint is simply another term for a route. When talking about APIs many people refer to the routes you visit as an endpoint.git

上面这句英文,是官方给出的关于这篇文章的介绍。大概意思就是,端点只是路由的一种术语。在谈论api时,许多人将您访问的路由称为端点。github

1.Version Groups  版本组

 为了不和主程序自带的路由区分,这个包使用了它本身的路由器。所以,咱们必须首先得到一个dingoAPI路由器的实例来建立咱们的路由。以下:api

$api = app('Dingo\Api\Routing\Router');
若是你想要某个组响应多个版本的API,能够传递多版本数组。以下:
$api->version(['v1', 'v2'], function ($api) {

});
这里的版本号能够看做和框架的标准路由分组同样传递数组属性做为第二个参数。以下:
$api->version('v1', ['middleware' => 'foo'], function ($api) {

});

你也能为你某个版本中的路由,统一一些属性。以下:数组

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

2.Creating Endpoints  建立路由

一旦你拥有一个版本组,你就可使用$api 在这个版本组中,建立路由。app

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

由于每一个版本组都是不相关的,相同的url路由,能够在不一样的版本组中,做出不一样的响应。框架

$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');
});

你也能够在不一样的版本中,使用各自的方法注册资源和控制器。url

提醒,你须要为控制器添加说明完整的命名空间(namespace),.例如:App\Http\Controllersspa

3.Named Routes And Generating URLs  命名路由并生成URL

命名你的路由可使你方便的生成他们的 URL。你能够跟 Laravel 同样的方法命名你的路由。

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

如今你能够经过路由别名,生成这个别名的URL。

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

4.Viewing Routes In The Console 在特定的控制台上显示路由

若是你使用Laravel 5.1, 你能够经过使用Artisan命令查看。

$ php artisan api:routes

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

相关文章
相关标签/搜索