该控制器类从 yii\rest\ActivrController 类扩展,它实现通用的 RESTful 动作。
我们指定 $modelClass 属性使得控制器知道使用哪个模型操作数据。
第1步 - 创建一个 UserController.php 控制器在 controllers 文件夹内。
<?php namespace app\controllers; use yii\rest\ActiveController; class UserController extends ActiveController { public $modelClass = 'app\models\MyUser'; } ?>
接下来,需要设置 urlManager 组件,使用户的数据可以访问,以及使用有意义的 HTTP 动词和漂亮网址来操纵。
为了访问让 API 以 JSON 数据格式返回,还应该配置应用程序组件的解析器(parsers)属性。
第2步 - 修改 config/web.php 文件如下代码 -
<?php $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is //required by cookie validation 'cookieValidationKey' => 'xuhuhu.com', ], 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ], 'errorHandler' => [ 'errorAction' => 'site/error', ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', // send all mails to a file by default. You have to set // 'useFileTransport' to false and configure a transport // for the mailer to send real emails. 'useFileTransport' => true, ], 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], 'urlManager' => [ 'enablePrettyUrl' => true, 'enableStrictParsing' => true, 'showScriptName' => false, 'rules' => [ ['class' => 'yii\rest\UrlRule', 'controller' => 'user'], ], ],'request' => ['class' => '\yii\web\Request','enableCookieValidation' => false,'parsers' => ['application/json' => 'yii\web\JsonParser',],'cookieValidationKey' => 'Oxuhuhu.com2trde1xww-M97_7QvwPo-5zaixian@#720',],'db' => require(__DIR__ . '/db.php'), ], 'modules' => [ 'admin' => [ 'class' => 'app\modules\hello\Admin', ], ], 'params' => $params, ]; if (YII_ENV_DEV) { // 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; ?>
使用一个最小实例来说明,上面刚刚建立一个RESTful API,用于访问用户数据。这些API包括 -
-
GET /users − 进行逐页读取所有用户
-
HEAD /users − 显示用户列表概述信息
-
POST /users − 创建一个新用户
-
GET /users/20 − 返回用户ID为 20 的详细信息
-
HEAD /users/20 − 显示用户ID为20的用户概述信息
-
PATCH /users/ 20 和 PUT /users/20 − 更新用户ID为20的用户信息
-
DELETE /users/20 − 删除用户ID为20的用户信息
-
OPTIONS /users − 显示端点 /users 支持的动词
-
OPTIONS /users/20 − 显示端点 /users/20 支持的动词
请注意,Yii会自动复数化控制器名称。
第3步 - 现在,打开Postman,切入:http://localhost:8080/users ,然后点击“Send”。将会看到以下内容。

第4步 - 创建一个新用户,修改请求类型为:POST,添加两个主体(Body)参数:name 和 email,并点击 “Send”。

第5步 - 可以使用 fields 参数来指定哪些字段应包函在结果中。
例如,URL => http://localhost:8080/users?fields=id,name 将只返回如下面图中显示的 id 和 name 字段 。
上一篇:
Yii RESTful API
下一篇:
Yii字段