リソースクラスを作成し、リソースデータのフォーマット方法を指定したら、次にすべきことは、RESTful APIを通じてエンドユーザにリソースを公開するためのコントローラアクションを作成することです。
Yiiは、RESTfulアクションの作成を簡略化するために、2つのベースコントローラクラスを提供しています:yii\rest\Controllerとyii\rest\ActiveController。これらの2つのコントローラの違いは、後者がアクティブレコードとして表現されるリソースを扱うために特別に設計されたデフォルトのアクションセットを提供していることです。したがって、アクティブレコードを使用しており、提供されている組み込みのアクションに慣れている場合は、コントローラクラスをyii\rest\ActiveControllerから拡張することを検討できます。これにより、最小限のコードで強力なRESTful APIを作成できます。
yii\rest\Controllerとyii\rest\ActiveControllerの両方が以下の機能を提供します。その一部は次のセクションで詳細に説明します。
yii\rest\ActiveController は、さらに以下の機能を提供します。
index
, view
, create
, update
, delete
, options
;新しいコントローラークラスを作成する際、コントローラークラスの命名規則は、リソースのタイプ名を使用し、単数形を使用することです。たとえば、ユーザー情報を提供するコントローラーは、UserController
と名付けることができます。
新しいアクションの作成は、Webアプリケーションのアクションの作成と似ています。唯一の違いは、render()
メソッドを呼び出してビューを使用して結果をレンダリングする代わりに、RESTfulアクションではデータを直接返すことです。シリアライザとレスポンスオブジェクトは、元のデータからリクエストされた形式への変換を処理します。例:
public function actionView($id)
{
return User::findOne($id);
}
yii\rest\Controller によって提供されるほとんどのRESTful API機能は、フィルターの観点から実装されています。特に、次のフィルターがリストされた順序で実行されます。
これらの名前付きフィルターは、behaviors() メソッドで宣言されています。このメソッドをオーバーライドして、個々のフィルターを設定したり、一部を無効にしたり、独自のフィルターを追加したりできます。たとえば、HTTP基本認証のみを使用する場合は、次のコードを記述できます。
use yii\filters\auth\HttpBasicAuth;
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::class,
];
return $behaviors;
}
コントローラーにCross-Origin Resource Sharingフィルターを追加することは、上記で説明した他のフィルターを追加するよりも少し複雑です。これは、CORSフィルターは認証メソッドの前に適用する必要があるため、他のフィルターとは少し異なるアプローチが必要になるためです。また、ブラウザが事前に認証情報を送信する必要なく、リクエストを作成できるかどうかを安全に判断できるように、CORSプリフライトリクエストでは認証を無効にする必要があります。以下は、yii\filters\Corsフィルターをyii\rest\ActiveControllerから拡張された既存のコントローラーに追加するために必要なコードを示しています。
use yii\filters\auth\HttpBasicAuth;
public function behaviors()
{
$behaviors = parent::behaviors();
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::class,
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
ActiveController
の拡張 ¶コントローラークラスがyii\rest\ActiveControllerから拡張されている場合は、そのmodelClassプロパティを、このコントローラーを通じて提供する予定のリソースクラスの名前に設定する必要があります。クラスはyii\db\ActiveRecordから拡張する必要があります。
デフォルトでは、yii\rest\ActiveControllerは次のアクションを提供します。
これらのすべてのアクションは、actions()メソッドを通じて宣言されます。次の例に示すように、actions()
メソッドをオーバーライドして、これらのアクションを設定したり、一部を無効にしたりできます。
public function actions()
{
$actions = parent::actions();
// disable the "delete" and "create" actions
unset($actions['delete'], $actions['create']);
// customize the data provider preparation with the "prepareDataProvider()" method
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider()
{
// prepare and return a data provider for the "index" action
}
利用可能な構成オプションについては、個々のアクションクラスのクラスリファレンスを参照してください。
RESTful APIを通じてリソースを公開する場合、多くの場合、現在のユーザーがリクエストされたリソースにアクセスして操作する権限を持っているかどうかを確認する必要があります。yii\rest\ActiveControllerを使用すると、次の例のように、checkAccess()メソッドをオーバーライドすることで、これを行うことができます。
/**
* Checks the privilege of the current user.
*
* 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.
*
* @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 = [])
{
// check if the user can access $action and $model
// throw ForbiddenHttpException if access should be denied
if ($action === 'update' || $action === 'delete') {
if ($model->author_id !== \Yii::$app->user->id)
throw new \yii\web\ForbiddenHttpException(sprintf('You can only %s articles that you\'ve created.', $action));
}
}
checkAccess()
メソッドは、yii\rest\ActiveControllerのデフォルトアクションによって呼び出されます。新しいアクションを作成し、アクセスチェックも実行する場合は、新しいアクションでこのメソッドを明示的に呼び出す必要があります。
ヒント: ロールベースのアクセス制御(RBAC)コンポーネントを使用して、
checkAccess()
を実装できます。
タイプミスを見つけた場合、またはこのページを改善する必要があると思われる場合は?
githubで編集する !
コメントするには、サインアップまたはログインしてください。