这篇说下yii2.0
开发 API
吧,使用 RESTful
API模式php
这是安装Yii2.0的首选方法。若是你尚未安装 Composer
,你能够按照这里的说明进行安装。mysql
安装完 Composer
,运行下面的命令来安装 Composer Asset
插件:git
php composer.phar global require "fxp/composer-asset-plugin:^1.2.0"
复制代码
安装高级的应用程序模板,运行下面的命令:github
php composer.phar create-project yiisoft/yii2-app-advanced advanced 2.0.13
复制代码
cd advanced
init
复制代码
打开 common\config\main-local.php
,配置数据库链接信息web
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=yiiapi',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
],
复制代码
migrate
数据库迁移yii migrate
复制代码
打开api\config\main.php
修改id
,controllerNamespace
:sql
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'api\controllers',
]
复制代码
打开common\config\main.php
开启url
路由美化规则数据库
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
复制代码
打开common\config\bootstrap.php
添加如下别名json
Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
复制代码
不少同窗在看了我这个教程,说是运行不起来、一直是404,而后就问我为何?我看了好多,他们都是本地使用 Apache
,而且 index.php
文件没有隐藏,他们访问地址也不叫 index.php
。因此在此说明一下吧bootstrap
Apache 配置api
# 设置文档根目录为 "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应用,目的是便于维护,能够避免如下问题
frontend
为前台目录;backend
为后台目录;api
为api目录接下来打开 api\controllers
新建一个User控制器,继承 yii\rest\ActiveController
,命名为 UserController
,代码以下:
<?php
namespace api\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController {
public $modelClass = 'common\models\User';
}
复制代码
这里建立 user
控制器继承 yii\rest\ActiveController
并指定要操做的模型
配置 request
应用程序组件的 parsers
属性使用 yii\web\JsonParser
用于 JSON
输入
打开配置文件 api\config\main-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' => 'yii\web\JsonParser',
],
],
],
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
复制代码
为刚才的 user
控制器添加url美化规则
打开 api\config\main.php
修改 components
属性,添加下列代码:
...
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule',
'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
这种方式来进行访问,好吧,能够,知足你,只是不推荐
继续打开配置文件api\config\main.php
修改刚才添加的 urlManager
以下:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize' => false, //设置为false 就能够去掉复数形式了
],
],
]
复制代码
加入 'pluralize' => false,
就表示去掉复数形式了,再次强调不推荐
ok,在控制器中咱们没有写任何一句代码,他就给咱们生成许多方法,可是有时候咱们可能须要修改一些代码,来达到咱们想要的效果,好比连表查询,而后再返回数据
接下来咱们就实现这样的功能:
打开刚才新建的user
控制器, 重写 action
方法:
<?php
namespace api\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController {
public $modelClass = 'common\models\User';
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 api\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'common\models\User';
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
,报错?找不到?
报错就对了,那是由于咱们没有设置其余路由访问
修改 api\config\main.php
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule',
'controller' => 'user',
//'pluralize' => false, //设置为false 就能够去掉复数形式了
'extraPatterns'=>[
'GET send-email'=>'send-email'
],
],
],
]
复制代码
接下来从新访问就没有问题了,ps:你本身编写的任何 action
都要在 extraPatterns
进行配置
差点忘了 状态码
这个东西,咱们如今全部的东西返回来的都是一个 JSON
,加入没有数据局返回的是空的数组,因此这确定不行啊,咱们得加上 一些特定的状态码 来标识这些数据啊,怎么加?
继续修改 api\config\main.php
在 components
添加以下代码:
'response' => [
'class' => 'yii\web\Response',
'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,你应该具体状况具体对待,切记不要乱使用 任意加各类标识,请 遵循这些 规范 状态码
是否是以为还少了点什么?认证
对就是 认证
,就差 认证
就完美了,篇幅有限,内容多了反而影响阅读兴趣,下篇进行 认证
介绍
感谢如下,特别是 魏曦老师的视频教程
不足之处,欢迎指正