├─assets│ AppAsset.php├─config│ bootstrap.php│ main-local.php│ main.php│ params-local.php│ params.php├─runtime└─web│ index.php├─assets└─css可以看出其目录结构基本上同backend没有其他差异,因为我们就是拷贝backend项目,只是做了部分优化。
"components" => [// other config"urlManager" => ["enablePrettyUrl" => true,"showScriptName" => false,"enableStrictParsing" =>true,"rules" => [],]],最后只需要在应用入口同级增加.htaccess文件就好,我们以apache为例
Options +FollowSymLinksIndexIgnore */*RewriteEngine on# if a directory or a file exists, use it directlyRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d# otherwise forward it to index.phpRewriteRule . index.phpRewriteRule .svn/ /404.htmlRewriteRule .git/ /404.html3、利用gii生成测试modulesCREATE TABLE `goods` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(100) NOT NULL DEFAULT "",PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `goods` VALUES ("1", "11111");INSERT INTO `goods` VALUES ("2", "22222");INSERT INTO `goods` VALUES ("3", "333");INSERT INTO `goods` VALUES ("4", "444");INSERT INTO `goods` VALUES ("5", "555");接着我们先利用gii生成modules后,再利用gii模块,按照下图中生成goods信息



现在,我们的api目录结构应该多个下面这几个目录
│├─models│ Goods.php│├─modules│ └─v1│ │ Module.php│ ││ ├─controllers│ │ DefaultController.php│ │ GoodsController.php│ ││ └─views│ └─default│ index.php4、重新配置控制器
<?phpnamespace apimodulesv1controllers;use yii
estActiveController;class GoodsController extends ActiveController{public $modelClass = "apimodelsGoods";}5、为Goods配置Url规则"rules" => [["class" => "yii estUrlRule","controller" => ["v1/goods"]],]6、模拟请求操作

从上面截图中可以清楚的看到,GET /v1/goods 已经能够很方便的获取我们表中的数据了。
当然,yii2还对该api封装了如下操作:
GET /users: 逐页列出所有用户
HEAD /users: 显示用户列表的概要信息
POST /users: 创建一个新用户
GET /users/123: 返回用户 123 的详细信息
HEAD /users/123: 显示用户 123 的概述信息
PATCH /users/123 and PUT /users/123: 更新用户123
DELETE /users/123: 删除用户123
OPTIONS /users: 显示关于末端 /users 支持的动词
OPTIONS /users/123: 显示有关末端 /users/123 支持的动词
不信的话我们可以利用postman发送一个post请求到/v1/goods,我们会发现成功创建了一个新的商品。
需要提醒的是,操作中还请细心且注意:
如果你的控制器末端不是复数(比如是blog非blogs)请保证请求的时候是复数!这是因为在RESTful架构中,网址中只能有名词而不能包含动词,名词又往往与数据表相对应,数据表呢又是一个“集合”,因此该名词往往是复数的形式。
7、关于授权认证
为什么需要授权认证?这在一般的操作中是需要的。比如说用户要设置自己的信息。
为了对yii2 restful授权认证说的更清楚,我们将会以两个两种不同的方法进行说明。
首先需要开启认证:
假设我们已经按照第3步创建了包含字段access-token的数据表user,而且利用gii上生成了相应的model和controller
配置main.php文件
"components" => ["user" => [ "identityClass" => "commonmodelsUser","enableAutoLogin" => true,"enableSession"=>false],],为控制器配置authenticator行为指定认证方式
<?phpnamespace apimodulesv1controllers;use yii
estActiveController;use yiihelpersArrayHelper;use yiifiltersauthQueryParamAuth;class UserController extends ActiveController{public $modelClass = "apimodelsUser";public function behaviors() {return ArrayHelper::merge (parent::behaviors(), [ "authenticator" => [ "class" => QueryParamAuth::className() ] ] );}}最后我们还需要在identityClass中实现findIdentityByAccessToken方法public static function findIdentityByAccessToken($token, $type = null){return static::findOne(["access_token" => $token, "status" => self::STATUS_ACTIVE]);}如此一来,我们先通过postman模拟不带access-token请求看结果{"name": "Unauthorized","message": "You are requesting with an invalid credential.","code": 0,"status": 401,"type": "yii\web\UnauthorizedHttpException"}提示401 我们没有权限访问!use yiifiltersRateLimitInterface;use yiiwebIdentityInterface;class User extends ActiveRecord implements IdentityInterface, RateLimitInterface{// other code ...... // 返回某一时间允许请求的最大数量,比如设置10秒内最多5次请求(小数量方便我们模拟测试)public function getRateLimit($request, $action){ return [5, 10]; }// 回剩余的允许的请求和相应的UNIX时间戳数 当最后一次速率限制检查时public function loadAllowance($request, $action){ return [$this->allowance, $this->allowance_updated_at]; } // 保存允许剩余的请求数和当前的UNIX时间戳public function saveAllowance($request, $action, $allowance, $timestamp){ $this->allowance = $allowance; $this->allowance_updated_at = $timestamp; $this->save(); } }需要注意的是,你仍然需要在数据表User中新增加两个字段{"name": "Too Many Requests","message": "Rate limit exceeded.","code": 0,"status": 429,"type": "yii\web\TooManyRequestsHttpException"}9、关于版本