鍍金池/ 教程/ PHP/ 控制器
查詢構(gòu)建器
HTTP 緩存
單元測試
資源
數(shù)據(jù)庫遷移
Fixtures
收集列表輸入
認證
助手類
緩存
數(shù)據(jù)緩存
最佳安全實踐
響應格式
使用 Gii 生成代碼
服務定位器
性能優(yōu)化
資源
多模型的復合表單
控制器
Html 幫助類
運行機制概述
快速入門
屬性(Property)
使用表單
配置測試環(huán)境
數(shù)據(jù)提供者
使用數(shù)據(jù)庫
授權(quán)
輸入驗證
類自動加載(Autoloading)
版本
響應
Sessions 和 Cookies
數(shù)組助手類
創(chuàng)建你自己的應用程序結(jié)構(gòu)
文件上傳
路由
收發(fā)郵件
模型
小部件
更上一層樓
頁面緩存
請求
片段緩存
排序
處理密碼
數(shù)據(jù)小部件
模塊
事件
控制器
從 Yii 1.1 升級
應用組件
驗收測試
入口腳本
總覽
Url 幫助類
行為
速率限制
控制臺命令
依賴注入容器
視圖
功能測試
錯誤處理
過濾器
主題
應用主體
引入第三方代碼
共享托管環(huán)境
測試
擴展
路由
使用模板引擎
核心驗證器(Core Validators)
分頁
數(shù)據(jù)庫訪問 (DAO)
配置
創(chuàng)建表單
日志
安裝 Yii
客戶端腳本使用
組件(Component)
說聲 Hello
運行應用
數(shù)據(jù)格式器
認證
錯誤處理
別名(Aliases)
Active Record
啟動引導(Bootstrapping)
國際化

控制器

在創(chuàng)建資源類和指定資源格輸出式化后,下一步就是創(chuàng)建控制器操作將資源通過 RESTful APIs 展現(xiàn)給終端用戶。

Yii 提供兩個控制器基類來簡化創(chuàng)建 RESTful 操作的工作:[[yii\rest\Controller]] 和 [[yii\rest\ActiveController]],兩個類的差別是后者提供一系列將資源處理成Active Record的操作。因此如果使用Active Record內(nèi)置的操作會比較方便,可考慮將控制器類繼承[[yii\rest\ActiveController]],它會讓你用最少的代碼完成強大的 RESTful APIs.

[[yii\rest\Controller]] 和 [[yii\rest\ActiveController]] 提供以下功能,一些功能在后續(xù)章節(jié)詳細描述:

[[yii\rest\ActiveController]] 額外提供一下功能:

  • 一系列常用操作: index, view, create, update, delete, options;
  • 對操作和資源進行用戶認證.

創(chuàng)建控制器類

當創(chuàng)建一個新的控制器類,控制器類的命名最好使用資源名稱的單數(shù)格式,例如,提供用戶信息的控制器可命名為UserController.

創(chuàng)建新的操作和 Web 應用中創(chuàng)建操作類似,唯一的差別是 Web 應用中調(diào)用render()方法渲染一個視圖作為返回值,對于 RESTful 操作直接返回數(shù)據(jù),[[yii\rest\Controller::serializer|serializer]] 和[[yii\web\Response|response object]] 會處理原始數(shù)據(jù)到請求格式的轉(zhuǎn)換,例如

public function actionView($id)
{
    return User::findOne($id);
}

過濾器

[[yii\rest\Controller]]提供的大多數(shù) RESTful API 功能通過過濾器實現(xiàn).特別是以下過濾器會按順序執(zhí)行:

  • [[yii\filters\ContentNegotiator|contentNegotiator]]: 支持內(nèi)容協(xié)商,在 響應格式化 一節(jié)描述;
  • [[yii\filters\VerbFilter|verbFilter]]: 支持 HTTP 方法驗證; the Authentication section;
  • [[yii\filters\RateLimiter|rateLimiter]]: 支持頻率限制,在頻率限制 一節(jié)描述.

這些過濾器都在[[yii\rest\Controller::behaviors()|behaviors()]]方法中聲明,可覆蓋該方法來配置單獨的過濾器,禁用某個或增加你自定義的過濾器。例如,如果你只想用 HTTP 基礎認證,可編寫如下代碼:

use yii\filters\auth\HttpBasicAuth;

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => HttpBasicAuth::className(),
    ];
    return $behaviors;
}

繼承 ActiveController

如果你的控制器繼承[[yii\rest\ActiveController]],應設置[[yii\rest\ActiveController::modelClass||modelClass]] 屬性為通過該控制器返回給用戶的資源類名,該類必須繼承[[yii\db\ActiveRecord]].

自定義操作

[[yii\rest\ActiveController]] 默認提供一下操作:

  • [[yii\rest\OptionsAction|options]]: 返回支持的 HTTP 方法.

所有這些操作通過[[yii\rest\ActiveController::actions()|actions()]] 方法申明,可覆蓋actions()方法配置或禁用這些操作,如下所示:

public function actions()
{
    $actions = parent::actions();

    // 禁用"delete" 和 "create" 操作
    unset($actions['delete'], $actions['create']);

    // 使用"prepareDataProvider()"方法自定義數(shù)據(jù) provider 
    $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];

    return $actions;
}

public function prepareDataProvider()
{
    // 為"index"操作準備和返回數(shù)據(jù) provider
}

請參考獨立操作類的參考文檔學習哪些配置項有用。

執(zhí)行訪問檢查

通過 RESTful APIs 顯示數(shù)據(jù)時,經(jīng)常需要檢查當前用戶是否有權(quán)限訪問和操作所請求的資源,在[[yii\rest\ActiveController]]中,可覆蓋[[yii\rest\ActiveController::checkAccess()|checkAccess()]]方法來完成權(quán)限檢查。

/**
 * Checks the privilege of the current user. 檢查當前用戶的權(quán)限
 *
 * This method should be overridden to check whether the current user has the privilege
 * to run the specified action against the specified data model.
 * If the user does not have access, a [[ForbiddenHttpException]] should be thrown.
 * 本方法應被覆蓋來檢查當前用戶是否有權(quán)限執(zhí)行指定的操作訪問指定的數(shù)據(jù)模型
 * 如果用戶沒有權(quán)限,應拋出一個[[ForbiddenHttpException]]異常
 *
 * @param string $action the ID of the action to be executed
 * @param \yii\base\Model $model the model to be accessed. If null, it means no specific model is being accessed.
 * @param array $params additional parameters
 * @throws ForbiddenHttpException if the user does not have access
 */
public function checkAccess($action, $model = null, $params = [])
{
    // 檢查用戶能否訪問 $action 和 $model
    // 訪問被拒絕應拋出 ForbiddenHttpException 
}

checkAccess() 方法默認會被[[yii\rest\ActiveController]]默認操作所調(diào)用,如果創(chuàng)建新的操作并想執(zhí)行權(quán)限檢查,應在新的操作中明確調(diào)用該方法。

提示: 可使用Role-Based Access Control (RBAC) 基于角色權(quán)限控制組件實現(xiàn)checkAccess()。