控制器(Controllers)

2018-02-24 15:40 更新

控制器

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

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

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

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

  • 一系列常用操作:?index,?view,?create,?update,?delete,?options;
  • 對(duì)操作和資源進(jìn)行用戶認(rèn)證.

創(chuàng)建控制器類

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

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

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

過(guò)濾器

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

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

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

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 屬性 為通過(guò)該控制器返回給用戶的資源類名,該類必須繼承yii\db\ActiveRecord.

自定義操作

yii\rest\ActiveController 默認(rèn)提供一下操作:

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

所有這些操作通過(guò)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"操作準(zhǔn)備和返回?cái)?shù)據(jù)provider
}

請(qǐng)參考獨(dú)立操作類的參考文檔學(xué)習(xí)哪些配置項(xiàng)有用。

執(zhí)行訪問(wèn)檢查

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

/**
 * Checks the privilege of the current user. 檢查當(dāng)前用戶的權(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)被覆蓋來(lái)檢查當(dāng)前用戶是否有權(quán)限執(zhí)行指定的操作訪問(wèn)指定的數(shù)據(jù)模型
 * 如果用戶沒(méi)有權(quán)限,應(yīng)拋出一個(gè)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 = [])
{
    // 檢查用戶能否訪問(wèn) $action 和 $model
    // 訪問(wèn)被拒絕應(yīng)拋出ForbiddenHttpException 
}

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

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

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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)