Yii動作使用RESTful API


該控制器類從 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' => 'tw511.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' => 'Otw511.com2trde1xww-M97_7QvwPo-5yiiBai@#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