1. 程式人生 > >yii restful api

yii restful api

模型 tty ocs calling nag pfile script dsa har

一、創建數據庫

首先,在mysql中創建一個名為yii2basic的數據庫,並創建一張名為player的表。

二、配置

1.app/config/db.php
  1. <?php
  2. return [
  3. ‘class‘ => ‘yii\db\Connection‘,
  4. ‘dsn‘ => ‘mysql:host=localhost;dbname=yii2basic‘,
  5. ‘username‘ => ‘root‘,
  6. ‘password‘ => ‘‘,
  7. ‘charset‘ => ‘utf8‘,
  8. ];
將此處的用戶名和密碼更改為本地對應。 2.app/config/web.php

  1. ‘urlManager‘ => [
  2. ‘enablePrettyUrl‘ => true,
  3. ‘enableStrictParsing‘ => true,
  4. ‘showScriptName‘ => false,
  5. ‘rules‘ => [
  6. [‘class‘ => ‘yii\rest\UrlRule‘, ‘controller‘ => ‘player‘],
  7. ],
  8. ],
在components下添加url配置。

3.創建.htaccess 在Yii項目下創建.htaccess,在app/web下創建,其內容為:
  1. Options +FollowSymLinks
  2. IndexIgnore /
  3. RewriteEngine on
  4. RewriteCond %{REQUEST_FILENAME} !-f
  5. RewriteCond %{REQUEST_FILENAME} !-d
  6. RewriteRule . index.php

三、創建一個控制器

首先,創建一個控制器類 app\controllers\PlayerController

如下,


  1. namespace app\controllers;
  2. use yii\rest\ActiveController;
  3. class UserController extends ActiveController
  4. {
  5. public $modelClass = ‘app\models\Player‘;
  6. public $serializer = ‘yii\rest\Serializer‘;
  7. public function checkAccess()
  8. {
  9. }
  10. }

控制器類擴展自 yii\rest\ActiveController。通過指定 yii\rest\ActiveController::modelClass 作為 app\models\player, 控制器就能知道使用哪個模型去獲取和處理數據。

四、創建一個模型類

然後,創建一個模型類 app\model\Player 如下,


  1. <?php
  2. namespace app\models;
  3. use yii\db\ActiveRecord;
  4. use yii\web\Link;
  5. use yii\web\Linkable;
  6. use yii\helpers\Url;
  7. class Player extends ActiveRecord implements Linkable
  8. {
  9. public function fields()
  10. {
  11. return [
  12. // 字段名和屬性名相同
  13. ‘id‘,
  14. // 字段名為"email", 對應的屬性名為"email_address"
  15. ‘username‘,
  16. ‘password‘,
  17. ];
  18. }
  19. public function getLinks()
  20. {
  21. return [
  22. Link::REL_SELF => Url::to([‘user/view‘, ‘id‘ => $this->id], true),
  23. ];
  24. }
  25. }

到此根據官方文檔可知已經生成了對應的一系列API,格式參照Yii2.0 RESTful Web服務(1) 通過命令:
  1. curl -i -H "Accept:application/json" "http://localhost/YourAppName/web/players"
會接收到如下的信息:
  1. [
  2. {
  3. "id": 0,
  4. "username": "",
  5. "password": "",
  6. "_links": {
  7. "self": {
  8. "href": "http://localhost/first-Yii/web/player/view?id=0"
  9. }
  10. }
  11. },
  12. {
  13. "id": 1,
  14. "username": "dffdfdfd",
  15. "password": "sdsadsa",
  16. "_links": {
  17. "self": {
  18. "href": "http://localhost/first-Yii/web/player/view?id=1<span style="font-family: ‘Helvetica Neue‘, Helvetica, Arial, ‘Hiragino Sans GB‘, ‘Hiragino Sans GB W3‘, ‘WenQuanYi Micro Hei‘, ‘Microsoft YaHei UI‘, ‘Microsoft YaHei‘, sans-serif; white-space: pre-wrap;">"</span>
  19. }
  20. }
  21. }
  22. ]

使用Postman對功能進行測試發現,CURD操作中的CD操作行為正常,但是請求單條記錄的操作的則會返回如下的錯誤:
  1. {
  2. "name": "Exception",
  3. "message": "Calling unknown method: app\\models\\Player::serializeModel()",
  4. "code": 0,
  5. "type": "yii\\base\\UnknownMethodException",
  6. "file": "/Applications/XAMPP/xamppfiles/htdocs/first-Yii/vendor/yiisoft/yii2/base/Component.php",
  7. "line": 285,
  8. "stack-trace": [
  9. "#0 /Applications/XAMPP/xamppfiles/htdocs/first-Yii/vendor/yiisoft/yii2/rest/Serializer.php(137): yii\\base\\Component->__call(‘serializeModel‘, Array)",
  10. "#1 /Applications/XAMPP/xamppfiles/htdocs/first-Yii/vendor/yiisoft/yii2/rest/Serializer.php(137): app\\models\\Player->serializeModel()",
  11. "#2 /Applications/XAMPP/xamppfiles/htdocs/first-Yii/vendor/yiisoft/yii2/rest/Controller.php(97): yii\\rest\\Serializer->serialize(Object(app\\models\\Player))",
  12. "#3 /Applications/XAMPP/xamppfiles/htdocs/first-Yii/vendor/yiisoft/yii2/rest/Controller.php(75): yii\\rest\\Controller->serializeData(Object(app\\models\\Player))",
  13. "#4 /Applications/XAMPP/xamppfiles/htdocs/first-Yii/vendor/yiisoft/yii2/base/Controller.php(156): yii\\rest\\Controller->afterAction(Object(yii\\rest\\ViewAction), Object(app\\models\\Player))",
  14. "#5 /Applications/XAMPP/xamppfiles/htdocs/first-Yii/vendor/yiisoft/yii2/base/Module.php(454): yii\\base\\Controller->runAction(‘view‘, Array)",
  15. "#6 /Applications/XAMPP/xamppfiles/htdocs/first-Yii/vendor/yiisoft/yii2/web/Application.php(84): yii\\base\\Module->runAction(‘player/view‘, Array)",
  16. "#7 /Applications/XAMPP/xamppfiles/htdocs/first-Yii/vendor/yiisoft/yii2/base/Application.php(375): yii\\web\\Application->handleRequest(Object(yii\\web\\Request))",
  17. "#8 /Applications/XAMPP/xamppfiles/htdocs/first-Yii/web/index.php(12): yii\\base\\Application->run()",
  18. "#9 {main}"
  19. ]
  20. }
報錯提示調用了不存在的方法,由Yii2.0 初識 RESTful Serializer可知此處是一個對模型序列化的方法,返回到Controller的聲明中可以發現確實初始化了$serializer變量。可以看出:
  1. public function serialize($data)
  2. {
  3. if ($data instanceof Model && $data->serializeModel()) {
  4. return $this->serializeModelErrors($data);
  5. } elseif ($data instanceof Arrayable) {
  6. return $this->serializeModel($data);
  7. } elseif ($data instanceof DataProviderInterface) {
  8. return $this->serializeDataProvider($data);
  9. } else {
  10. return $data;
  11. }
  12. }
應當是此處傳入的$data並沒有serializeModel()方法,查找serializeModel()的定義,發現app/rest/Serializer::serializeModel();在此處有一個定義,可見傳入的數據並不一定會有serializeModel方法,除非傳入的數據已經是一個app/rest/Serializer的實例,那麽註釋掉$data->serializeModel()這個條件,進行測試,這次並沒有報錯,但是返回了一個空的結果集。 -------------------------------------------第一次更新---------------------------------------- 這次我對數據庫中沒有的記錄進行了查詢,這次返回的結果給了很大的提示:
  1. {
  2. "name": "Not Found",
  3. "message": "Object not found: 3",
  4. "code": 0,
  5. "status": 404,
  6. "type": "yii\\web\\NotFoundHttpException"
  7. }
確實數據庫中並沒有主鍵為3的這條記錄,所以在數據庫更換主鍵再進行測試,這次以username作為主鍵發現問題依然存在。

yii restful api