laravel 中安装 Dingo API 基本设置
安装
-
在项目
composer.json
文件最后添加"minimum-stability": "dev", "prefer-stable" : true
-
运行命令安装
composer require dingo/api:^2.0.0-beta1
-
发布配置文件
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
配置
在 .env
文件里添加配置
# dingo
API_SUBTYPE=项目名称
API_VERSION=v1
API_PREFIX=api
API_DEBUG=true
API_VERSION
为默认版本号
API_PREFIX
为接口前缀
API_DEBUG
开启 debug 注意生产环境关闭
控制器
- 创建基础控制器
app/Http/Controllers/Api/Controller.php
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;
use App\Http\Controllers\Controller as BaseController;
class Controller extends BaseController
{
use Helpers;
}
- 其它接口控制器继承
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\Controller;
class UserController extends Controller
{
public function ft1()
{
return $this->response->array(['error'=>'0','data'=>[]]);
}
public function ft2(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required'
]);
return $this->response->array(['error'=>'0','data'=>$request->header()]);
}
}
路由文件
routes/api.php
$api = app('Dingo\Api\Routing\Router');
$api->version('v1',['namespace' => 'App\Http\Controllers\Api'], function ($api) {
$api->get('ft1','UserController@ft1');
$api->post('ft2','UserController@ft2');
});