Yii RESTful API


Yii提供實現了 RESTful API 以下有用的功能 -
  • 快速原型
  • 自定義物件序列化
  • 響應格式(支援預設JSON和XML)
  • 收集資料格式和驗證錯誤
  • 高效的路由
  • HATEOAS支援
  • 內建支援 OPTION 和 HEAD 動詞
  • 資料快取和HTTP快取
  • 認證和授權
  • 速率限制
在動作中顯示如何使用 RESTful API ,我們需要準備一些資料。

準備資料庫

第1步 - 建立一個新的資料庫。資料庫可以通過以下兩種方式進行。
  • 在終端執行 mysql -u root –p

  • 登入資料後,通過執行 CREATE DATABASE mystudy CHARACTER SET utf8 COLLATE utf8_general_ci; 建立一個新的資料庫;

第2步 - 在 config/db.php 檔案中組態資料庫連線。下面的組態可根據自己的實際情況組態。
<?php
   return [
      'class' => 'yii\db\Connection',
      'dsn' => 'mysql:host = localhost;dbname = mystudy',
      'username' => 'root',
      'password' => '',
      'charset' => 'utf8',
   ];
?>

第3步 - 在專案根檔案夾執行:yii migrate/create test_table 。此命令將用於建立管理資料庫資料庫遷移。 migrations檔案會出現在專案的根的 migrations 檔案夾中。
Yii RESTful API

第4步 - 修改遷移檔案(在本範例中生成的是:m160529_014611_test_table.php),並使用以下這些程式碼。
<?php
   use yii\db\Schema;
   use yii\db\Migration;
   class m160529_014611_test_table extends Migration {
      public function up() {
         $this->createTable("user", [
            "id" => Schema::TYPE_PK,
            "name" => Schema::TYPE_STRING,
            "email" => Schema::TYPE_STRING,
         ]);
         $this->batchInsert("user", ["name", "email"], [
            ["User1", "[email protected]"],
            ["User2", "[email protected]"],
            ["User3", "[email protected]"],
            ["User4", "[email protected]"],
            ["User5", "[email protected]"],
            ["User6", "[email protected]"],
            ["User7", "[email protected]"],
            ["User8", "[email protected]"],
            ["User9", "[email protected]"],
            ["User10", "[email protected]"],
            ["User11", "[email protected]"],
         ]);
      }
      public function down() {
         //$this->dropTable('user');
      }
   }
?>
上述遷移建立使用者表,它包含了以下這些欄位:id, name, 和 email。它還增加了一些演示使用者帳號。
第5步 - 在專案的根目錄內執行: yii migrate  來遷移應用到資料庫。執行結果如下圖所示:

第6步-現在,我們需要為user表建立模型。為了簡便起見,我們將使用GII程式碼生成工具。在瀏覽器中開啟 url: http://localhost:8080/index.php?r=gii 。
然後,點選 「Model generator」 下的 「Start」按鈕。 填寫表名(「user」)和模型類(「MyUser」),單擊「Preview」按鈕,最後點選 「Generate」 按鈕。



MyUser 檔案憶經生成在 models 目錄。

安裝Postman

Postman 是開發RESTful服務一個使用方便的工具。它提供了用於構建請求一個有用的介面。

可以在 https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en  找到這個工具.

要安裝它,點選「Add to Chrome」按鈕。