Yii2.0 RESTful API 基础配置教程
- 2019 年 12 月 17 日
- 筆記
这篇说下yii2.0
开发 API
吧,使用 RESTful
API模式
安装Yii2.0
通过 Composer 安装
这是安装Yii2.0的首选方法。如果你还没有安装 Composer
,你可以按照这里的说明进行安装。
安装完 Composer
,运行下面的命令来安装 Composer Asset
插件:
php composer.phar global require "fxp/composer-asset-plugin:^1.2.0"
安装高级的应用程序模板,运行下面的命令:
php composer.phar create-project yiisoft/yii2-app-advanced advanced 2.0.13
初始化高级模板
cd advanced init
修改数据库连接属性
打开 commonconfigmain-local.php
,配置数据库连接信息
'db' => [ 'class' => 'yiidbConnection', 'dsn' => 'mysql:host=127.0.0.1;dbname=yiiapi', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', ],
执行 migrate
数据库迁移
yii migrate
拷贝backend目录,命名为api
打开apiconfigmain.php
修改id
,controllerNamespace
:
return [ 'id' => 'app-api', 'basePath' => dirname(__DIR__), 'controllerNamespace' => 'apicontrollers', ]
打开commonconfigmain.php
开启url
路由美化规则
'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ ], ],
打开commonconfigbootstrap.php
添加以下别名
Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
配置 Web 服务器
很多同学在看了我这个教程,说是运行不起来、一直是404,然后就问我为什么?我看了好多,他们都是本地使用 Apache
,并且 index.php
文件没有隐藏,他们访问地址也不叫 index.php
。所以在此说明一下吧
Apache 配置
# 设置文档根目录为 "path/to/api/web" DocumentRoot "path/to/api/web" <Directory "path/to/api/web"> # 开启 mod_rewrite 用于美化 URL 功能的支持(译注:对应 pretty URL 选项) RewriteEngine on # 如果请求的是真实存在的文件或目录,直接访问 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 如果请求的不是真实文件或目录,分发请求至 index.php RewriteRule . index.php # if $showScriptName is false in UrlManager, do not allow accessing URLs with script name RewriteRule ^index.php/ - [L,R=404] # ...其它设置... </Directory>
或者 在web 目录下新建一个 .htaccess
文件,填入以下内容(我这是从 Laravel 项目中拷贝过来的),同样可以起到隐藏 index.php
的效果
<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule>
Nginx 的配置
location / { # Redirect everything that isn't a real file to index.php try_files $uri $uri/ /index.php$is_args$args; }
为什么要单独创建API应用
单独创建API应用,目的是便于维护,可以避免以下问题
- 配置的冲突
- 控制器的命名不便
- url美化规则冲突
- 分工明确
frontend
为前台目录;backend
为后台目录;api
为api目录
接下来打开 apicontrollers
新建一个User控制器,继承 yiirestActiveController
,命名为 UserController
,代码如下:
<?php namespace apicontrollers; use yiirestActiveController; class UserController extends ActiveController { public $modelClass = 'commonmodelsUser'; }
这里创建 user
控制器继承 yiirestActiveController
并指定要操作的模型
启用JSON 输入
配置 request
应用程序组件的 parsers
属性使用 yiiwebJsonParser
用于 JSON
输入
打开配置文件 apiconfigmain-local.php
修改为如下代码:
<?php $config = [ 'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation 'cookieValidationKey' => 'P0r2XoT9LCUnyVlSgxBbJOqQxdCJ3i29', 'parsers' => [ 'application/json' => 'yiiwebJsonParser', ], ], ], ]; if (!YII_ENV_TEST) { // configuration adjustments for 'dev' environment $config['bootstrap'][] = 'debug'; $config['modules']['debug'] = [ 'class' => 'yiidebugModule', ]; $config['bootstrap'][] = 'gii'; $config['modules']['gii'] = [ 'class' => 'yiigiiModule', ]; } return $config;
配置URL规则
为刚才的 user
控制器添加url美化规则
打开 apiconfigmain.php
修改 components
属性,添加下列代码:
... 'urlManager' => [ 'enablePrettyUrl' => true, 'enableStrictParsing' => true, 'showScriptName' => false, 'rules' => [ ['class' => 'yiirestUrlRule', 'controller' => 'user' ], ], ] ...
ok,到此就成了一个 符合 RESTful
风格的API 看起来在控制器了什么也没有写,只是指定了一个模型,但是她的背后完成了很多的功能哦,列表如下:
GET /users
: 逐页列出所有用户HEAD /users
: 显示用户列表的概要信息POST /users
: 创建一个新用户GET /users/123
: 返回用户 123 的详细信息HEAD /users/123
: 显示用户 123 的概述信息PATCH /users/123
: and PUT /users/123: 更新用户123DELETE /users/123
: 删除用户123OPTIONS /users
: 显示关于末端 /users 支持的动词OPTIONS /users/123
: 显示有关末端 /users/123 支持的动词
如何访问呢
你可以使用 curl
命令进行访问,命令如下:
curl -i -H "Accept:application/json" "http://localhost/users"
命令行下还是比较麻烦的,也不方便测试,推荐使用 API
测试工具
这类的工具有很多,我就不一一列举了,这里推荐 Postman
,很好很强大,Chorme
也有插件,可以安装,这里我推荐直接下载软件安装调试,比较方便
你可能发现了 访问任何路由地址都是加的s
,users
, 为什么呢? 资源
,你要理解 资源
二字,既然是资源肯定是个集合,肯定有一大堆,所以要加上复数,我是这么理解的。
你说我就是不想加上s
,我就想采用http://localhost/user
这种方式来进行访问,好吧,可以,满足你,只是不推荐
继续打开配置文件apiconfigmain.php
修改刚才添加的 urlManager
如下:
'urlManager' => [ 'enablePrettyUrl' => true, 'enableStrictParsing' => true, 'showScriptName' => false, 'rules' => [ ['class' => 'yiirestUrlRule', 'controller' => 'user', 'pluralize' => false, //设置为false 就可以去掉复数形式了 ], ], ]
加入 'pluralize' => false,
就表示去掉复数形式了,再次强调不推荐
ok,在控制器中我们没有写任何一句代码,他就给我们生成许多方法,但是有时候我们可能需要修改一些代码,来达到我们想要的效果,比如连表查询,然后再返回数据
接下来我们就实现这样的功能:
打开刚才新建的user
控制器, 重写 action
方法:
<?php namespace apicontrollers; use yiirestActiveController; class UserController extends ActiveController { public $modelClass = 'commonmodelsUser'; public function actions() { $action= parent::actions(); // TODO: Change the autogenerated stub unset($action['index']); unset($action['create']); unset($action['update']); unset($action['delete']); return $action; } public function actionIndex() { //你的代码 } }
这样我们就可以重写他的代码了。哈哈
我们再新建一个自己的 action
<?php namespace apicontrollers; use yiirestActiveController; class UserController extends ActiveController { public $modelClass = 'commonmodelsUser'; public function actions() { $action= parent::actions(); // TODO: Change the autogenerated stub unset($action['index']); unset($action['create']); unset($action['update']); unset($action['delete']); return $action; } public function actionIndex() { //你的代码 } public function actionSendEmail() //假如是get请求 { //业务逻辑 } }
然后试着访问一下 http://localhost/users/send-email
,报错?找不到?
报错就对了,那是因为我们没有设置其他路由访问
修改 apiconfigmain.php
'urlManager' => [ 'enablePrettyUrl' => true, 'enableStrictParsing' => true, 'showScriptName' => false, 'rules' => [ ['class' => 'yiirestUrlRule', 'controller' => 'user', //'pluralize' => false, //设置为false 就可以去掉复数形式了 'extraPatterns'=>[ 'GET send-email'=>'send-email' ], ], ], ]
接下来重新访问就没有问题了,ps:你自己编写的任何 action
都要在 extraPatterns
进行配置
差点忘了 状态码
这个东西,我们现在所有的东西返回来的都是一个 JSON
,加入没有数据局返回的是空的数组,所以这肯定不行啊,我们得加上 一些特定的状态码 来标识这些数据啊,怎么加?
继续修改 apiconfigmain.php
在 components
添加如下代码:
'response' => [ 'class' => 'yiiwebResponse', 'on beforeSend' => function ($event) { $response = $event->sender; $response->data = [ 'success' => $response->isSuccessful, 'code' => $response->getStatusCode(), 'message' => $response->statusText, 'data' => $response->data, ]; $response->statusCode = 200; }, ],
这里统一使用 200
来表示,当然并不是所有的都是 200,你应该具体情况具体对待,切记不要乱使用 任意加各种标识,请 遵循这些 规范 状态码