Files
yii2/docs/guide-zh-CN/rest-controllers.md
Funson Lee 031ef95b46 for check
2015-01-04 10:39:07 +08:00

11 KiB
Raw Blame History

Controllers 控制器

After creating the resource classes and specifying how resource data should be formatted, the next thing to do is to create controller actions to expose the resources to end users through RESTful APIs. 在创建资源类和指定资源格输出式化后下一步就是创建控制器操作将资源通过RESTful APIs展现给终端用户。

Yii provides two base controller classes to simplify your work of creating RESTful actions: yii\rest\Controller and yii\rest\ActiveController. The difference between these two controllers is that the latter provides a default set of actions that are specifically designed to deal with resources represented as Active Record. So if you are using Active Record and are comfortable with the provided built-in actions, you may consider extending your controller classes from yii\rest\ActiveController, which will allow you to create powerful RESTful APIs with minimal code. Yii 提供两个控制器基类来简化创建RESTful 操作的工作:yii\rest\Controlleryii\rest\ActiveController 两个类的差别是后者提供一系列将资源处理成Active Record的操作。 因此如果使用Active Record内置的操作会比较方便,可考虑将控制器类 继承yii\rest\ActiveController它会让你用最少的代码完成强大的RESTful APIs.

Both yii\rest\Controller and yii\rest\ActiveController provide the following features, some of which will be described in detail in the next few sections: yii\rest\Controlleryii\rest\ActiveController 提供以下功能,一些功能在后续章节详细描述:

yii\rest\ActiveController in addition provides the following features: yii\rest\ActiveController 额外提供一下功能:

  • A set of commonly needed actions: index, view, create, update, delete, options;
  • User authorization in regarding to the requested action and resource.
  • 一系列常用操作: index, view, create, update, delete, options;
  • 对操作和资源进行用户认证.

Creating Controller Classes

创建控制器类

When creating a new controller class, a convention in naming the controller class is to use the type name of the resource and use singular form. For example, to serve user information, the controller may be named as UserController. 当创建一个新的控制器类,控制器类的命名最好使用资源名称的单数格式,例如,提供用户信息的控制器 可命名为UserController.

Creating a new action is similar to creating an action for a Web application. The only difference is that instead of rendering the result using a view by calling the render() method, for RESTful actions you directly return the data. The yii\rest\Controller::serializer and the yii\web\Response will handle the conversion from the original data to the requested format. For example, 创建新的操作和Web应用中创建操作类似唯一的差别是Web应用中调用render()方法渲染一个视图作为返回值, 对于RESTful操作直接返回数据yii\rest\Controller::serializeryii\web\Response 会处理原始数据到请求格式的转换,例如

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

Filters

过滤器

Most RESTful API features provided by yii\rest\Controller are implemented in terms of filters. In particular, the following filters will be executed in the order they are listed: yii\rest\Controller提供的大多数RESTful API功能通过过滤器实现. 特别是以下过滤器会按顺序执行:

These named filters are declared in the yii\rest\Controller::behaviors() method. You may override this method to configure individual filters, disable some of them, or add your own filters. For example, if you only want to use HTTP basic authentication, you may write the following code: 这些过滤器都在yii\rest\Controller::behaviors()方法中声明, 可覆盖该方法来配置单独的过滤器,禁用某个或增加你自定义的过滤器。 例如如果你只想用HTTP 基础认证,可编写如下代码:

use yii\filters\auth\HttpBasicAuth;

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

Extending ActiveController

继承 ActiveController

If your controller class extends from yii\rest\ActiveController, you should set its yii\rest\ActiveController::modelClass property to be the name of the resource class that you plan to serve through this controller. The class must extend from yii\db\ActiveRecord. 如果你的控制器继承yii\rest\ActiveController,应设置yii\rest\ActiveController::modelClass 属性 为通过该控制器返回给用户的资源类名,该类必须继承yii\db\ActiveRecord.

Customizing Actions

自定义操作

By default, yii\rest\ActiveController provides the following actions: yii\rest\ActiveController 默认提供一下操作:

All these actions are declared through the yii\rest\ActiveController::actions() method. You may configure these actions or disable some of them by overriding the actions() method, like shown the following, 所有这些操作通过yii\rest\ActiveController::actions() 方法申明,可覆盖actions()方法配置或禁用这些操作, 如下所示:

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

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

    // 使用"prepareDataProvider()"方法自定义数据provider 
    $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];

    return $actions;
}

public function prepareDataProvider()
{
    // 为"index"操作准备和返回数据provider
}

Please refer to the class references for individual action classes to learn what configuration options are available. 请参考独立操作类的参考文档学习哪些配置项有用。

Performing Access Check

执行访问检查

When exposing resources through RESTful APIs, you often need to check if the current user has the permission to access and manipulate the requested resource(s). With yii\rest\ActiveController, this can be done by overriding the yii\rest\ActiveController::checkAccess() method like the following, 通过RESTful APIs显示数据时经常需要检查当前用户是否有权限访问和操作所请求的资源yii\rest\ActiveController中,可覆盖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.
 * 本方法应被覆盖来检查当前用户是否有权限执行指定的操作访问指定的数据模型
 * 如果用户没有权限,应抛出一个[[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 
}

The checkAccess() method will be called by the default actions of yii\rest\ActiveController. If you create new actions and also want to perform access check, you should call this method explicitly in the new actions. checkAccess() 方法默认会被yii\rest\ActiveController默认操作所调用,如果创建新的操作并想执行权限检查, 应在新的操作中明确调用该方法。

Tip: You may implement checkAccess() by using the Role-Based Access Control (RBAC) component. 提示: 可使用Role-Based Access Control (RBAC) 基于角色权限控制组件实现checkAccess()