第三節: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命令同樣。

相關文章
相關標籤/搜索