Yii2 RESTful Web Service Quick Start的完整实例 [ 技术分享 ]
本文是Yii2 RESTful Web Service Quick Start的完整实例,使用的是MariaDB数据库,Yii2(Advanced template)。 官网文档只是关键代码,有些东东需要一定的经验才能配置、调试出来,小坑无数,所以在此我将完整实例代码贴出来供大家参考。
本文对应的Yii2 RESTful Web Service Quick Start技术文档官网网址:
http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
以下是源代码:
文件位置:D:\phpwork\advanced\frontend\controllers\UserController.php
<?php
namespace frontend\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController{
public $modelClass = 'frontend\models\User';
}
文件位置:D:\phpwork\advanced\frontend\models\User.php
<?php
namespace frontend\models;
use Yii;
class User extends \yii\db\ActiveRecord{
public static function tableName(){
return 'user';
}
public function rules(){
return [
[['username', 'auth_key', 'password_hash', 'email', 'created_at', 'updated_at'], 'required'],
[['status', 'created_at', 'updated_at'], 'integer'],
[['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['username'], 'unique'],
[['email'], 'unique'],
[['password_reset_token'], 'unique'],
];
}
public function attributeLabels(){
return [
'id' => 'ID',
'username' => 'Username',
'auth_key' => 'Auth Key',
'password_hash' => 'Password Hash',
'password_reset_token' => 'Password Reset Token',
'email' => 'Email',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
}
文件位置:D:\phpwork\advanced\frontend\web.htaccess
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
文件位置:D:\phpwork\advanced\frontend\config\main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'aliases' => [
'@name1' => '@app/path/to/path1',
'@name2' => 'path/to/path2',
],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'assetManager' => [
'linkAssets' => true,
],
'urlManager' => [
//简洁网址(PrettyUrl)配置:
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize'=>false,//禁用复数形式,建议使用
],
],
],
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
],
'params' => $params,
'controllerMap' => [
'article' => [
'class' => 'frontend\controllers\PostController',
'enableCsrfValidation' => false,
],
],
'language' => 'zh-CN',
];
相关表和数据的SQL语句:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`auth_key` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password_reset_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`status` smallint(6) NOT NULL DEFAULT '10',
`created_at` int(11) NOT NULL,
`updated_at` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `password_reset_token` (`password_reset_token`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'halo', '38j9ISlh85aYMI7M3-aMPNBB-E46VIIX', '$2y$13$sWtikd9ooVETqI4uQ/MXV.PsJGsUqTBE0yzotNY1QWaVWohmE3gZq', '0jLyds9yoCB91Su9ZIMUc9RYQk_USC4y_1473762490', 'xcwaop@263.net', '10', '1461664500', '1473762490');
INSERT INTO `user` VALUES ('4', 'akalaa', '38j9ISlh85aYMI7M3-aMPNBB-E46VIIX', '$2y$13$sWtikd9ooVETqI4uQ/MXV.PsJGsUqTBE0yzotNY1QWaVWohmE3gZq', '0jLyds9yoCB91Su9ZIMUc9RYak_USC4y_1473762490', 'allaa@263.net', '10', '1461664500', '1473762490');
INSERT INTO `user` VALUES ('5', 'oakala', '38j9ISlh85aYMI7M3-aMPNBB-E46VIIX', '$2y$13$sWtikd9ooVETqI4uQ/MXV.PsJGsUqTBE0yzotNY1QWaVWohmE3gZq', '0jLyds9yoCB91Su9ZIMUc9RYbk_USC4y_1473762490', 'allaa@163.net', '10', '1461664500', '1473762490');
INSERT INTO `user` VALUES ('7', 'woluo56', '38j9ISlh85aYMI7M3-aMPNBB-E46VIIX', '$2y$13$sWtikd9ooVETqI4uQ/MXV.PsJGsUqTBE0yzotNY1QWaVWohmE3gZq', '0jLyds9yoCB91Su9ZIMUc9nYbk_USC4y_1473762490', 'woluo@163.net', '10', '1461664500', '1473762490');
INSERT INTO `user` VALUES ('8', 'nmeingo', '38j9ISlh85aYMI7M3-aMPNBB-E46VIIX', '$2y$13$sWtikd9ooVETqI4uQ/MXV.PsJGsUqTBE0yzotNY1QWaVWohmE3gZq', '0jLyds9yoCB91Su9ZIoUc9nYbk_USC4y_1473762490', 'nmeingo@163.net', '10', '1461664500', '1473762490');
调试注意事项:
官网中的错误写法:
http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
根据上面这个官网教程写的例子('pluralize'=>true,默认值时),访问时是有问题的: 访问以下网址时报404错误(无此页面):
http://localhost/users/5
正确的写法是:(应返回id=5的记录详情信息)
http://localhost/user/5
需要注意的是,访问列表信息的链接是正确的(要用复数形式):
http://localhost/users
如果要保证访问列表信息和详情信息时都使用单数形式,需要在config\main.php加个参数:
'pluralize'=>false,
即:
D:\phpwork\advanced\frontend\config\main.php
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize'=>false,
],
],
],
在此列出在浏览器访问时的三种报错信息:
1、无此页面(访问网址错误)
网址:http://localhost/users/5
Not Found (#404)
页面未找到。
The above error occurred while the Web server was processing your request.
Please contact us if you think this is a server error. Thank you.
2017-04-21 15:20:44
2、没有找到id=2记录(正常访问)
网址:http://localhost/user/2
<response>
<name>Not Found</name>
<message>Object not found: 2</message>
<code>0</code>
<status>404</status>
<type>yii\web\NotFoundHttpException</type>
</response>
3、找到的id=5记录(正常访问)
网址:http://localhost/user/5
<response>
<id>5</id>
<username>oakala</username>
<auth_key>38j9ISlh85aYMI7M3-aMPNBB-E46VIIX</auth_key>
<password_hash>
$2y$13$sWtikd9ooVETqI4uQ/MXV.PsJGsUqTBE0yzotNY1QWaVWohmE3gZq
</password_hash>
<password_reset_token>0jLyds9yoCB91Su9ZIMUc9RYbk_USC4y_1473762490</password_reset_token>
<email>allaa@163.net</email>
<status>10</status>
<created_at>1461664500</created_at>
<updated_at>1473762490</updated_at>
</response>
(全文完)
共 3 条回复
-
经查证,关于以上单数、复数形式的错误真实原因:
frontend应用的配置与common的配置冲突
具体配置如下:
D:\phpwork\advanced\common\config\main.php'urlManager' => [ //'class' => 'yii\web\UrlManager', 'showScriptName' => true, 'enablePrettyUrl' => true, //将此rules删除后,frontend的单复数形式访问就一切正常了! 'rules' => array( '<controller:\w+>/<id:\d+>' => '<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>', '<controller:\w+>/<action:\w+>' => '<controller>/<action>', ), ],
D:\phpwork\advanced\frontend\config\main.php
'urlManager' => [ 'enablePrettyUrl' => true, 'enableStrictParsing' => false, 'showScriptName' => false, 'rules' => [ [ 'class' => 'yii\rest\UrlRule', 'controller' => 'user', // 'pluralize'=>false, ], ], ],
看来塔个干净的环境进行试验还是很重要的!此问题是在Yii2的basic版中被再次发现,特此更正一下!
-
-
阿江
最后登录:2024-03-03
在线时长:186小时21分
- 粉丝94
- 金钱16816
- 威望160
- 积分20276