控制器(Controllers)

2018-02-24 15:40 更新

控制器

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

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

過濾器

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

  • yii\filters\ContentNegotiator: 支持內(nèi)容協(xié)商,在?響應(yīng)格式化?一節(jié)描述;
  • yii\filters\VerbFilter: 支持HTTP 方法驗證; the?Authentication?section;
  • yii\filters\AuthMethod: 支持用戶認證,在認證一節(jié)描述;
  • yii\filters\RateLimiter: 支持頻率限制,在頻率限制?一節(jié)描述.

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

use yii\filters\auth\HttpBasicAuth;

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

繼承?ActiveController

如果你的控制器繼承yii\rest\ActiveController,應(yīng)設(shè)置yii\rest\ActiveController::modelClass 屬性 為通過該控制器返回給用戶的資源類名,該類必須繼承yii\db\ActiveRecord.

自定義操作

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

  • yii\rest\IndexAction: 按頁列出資源;
  • yii\rest\ViewAction: 返回指定資源的詳情;
  • yii\rest\CreateAction: 創(chuàng)建新的資源;
  • yii\rest\UpdateAction: 更新一個存在的資源;
  • yii\rest\DeleteAction: 刪除指定的資源;
  • yii\rest\OptionsAction: 返回支持的HTTP方法.

所有這些操作通過yii\rest\ActiveController::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
}

請參考獨立操作類的參考文檔學(xué)習(xí)哪些配置項有用。

執(zhí)行訪問檢查

通過RESTful APIs顯示數(shù)據(jù)時,經(jīng)常需要檢查當前用戶是否有權(quán)限訪問和操作所請求的資源, 在yii\rest\ActiveController中,可覆蓋yii\rest\ActiveController::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.
 * 本方法應(yīng)被覆蓋來檢查當前用戶是否有權(quán)限執(zhí)行指定的操作訪問指定的數(shù)據(jù)模型
 * 如果用戶沒有權(quán)限,應(yīng)拋出一個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
    // 訪問被拒絕應(yīng)拋出ForbiddenHttpException 
}

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

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

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號