# 控制器
在创建资源类和指定资源格输出式化后,下一步就是创建控制器操作将资源通过RESTful APIs展现给终端用户。
Yii 提供两个控制器基类来简化创建RESTful 操作的工作:yii\rest\Controller 和 yii\rest\ActiveController, 两个类的差别是后者提供一系列将资源处理成[Active Record](http://www.yiichina.com/doc/guide/2.0/db-active-record)的操作。 因此如果使用[Active Record](http://www.yiichina.com/doc/guide/2.0/db-active-record)内置的操作会比较方便,可考虑将控制器类 继承yii\rest\ActiveController,它会让你用最少的代码完成强大的RESTful APIs.
yii\rest\Controller 和 yii\rest\ActiveController 提供以下功能,一些功能在后续章节详细描述:
*   HTTP 方法验证;
*   [内容协商和数据格式化](http://www.yiichina.com/doc/guide/2.0/rest-response-formatting);
*   [认证](http://www.yiichina.com/doc/guide/2.0/rest-authentication);
*   [频率限制](http://www.yiichina.com/doc/guide/2.0/rest-rate-limiting).
yii\rest\ActiveController 额外提供一下功能:
*   一系列常用操作: `index`, `view`, `create`, `update`, `delete`, `options`;
*   对操作和资源进行用户认证.
## 创建控制器类
当创建一个新的控制器类,控制器类的命名最好使用资源名称的单数格式,例如,提供用户信息的控制器 可命名为`UserController`.
创建新的操作和Web应用中创建操作类似,唯一的差别是Web应用中调用`render()`方法渲染一个视图作为返回值, 对于RESTful操作直接返回数据,yii\rest\Controller::serializer 和 yii\web\Response 会处理原始数据到请求格式的转换,例如
~~~
public function actionView($id)
{
    return User::findOne($id);
}
~~~
## 过滤器
yii\rest\Controller提供的大多数RESTful API功能通过[过滤器](http://www.yiichina.com/doc/guide/2.0/structure-filters)实现. 特别是以下过滤器会按顺序执行:
*   yii\filters\ContentNegotiator: 支持内容协商,在 [响应格式化](http://www.yiichina.com/doc/guide/2.0/rest-response-formatting) 一节描述;
*   yii\filters\VerbFilter: 支持HTTP 方法验证; the [Authentication](http://www.yiichina.com/doc/guide/2.0/rest-authentication) section;
*   yii\filters\AuthMethod: 支持用户认证,在[认证](http://www.yiichina.com/doc/guide/2.0/rest-authentication)一节描述;
*   yii\filters\RateLimiter: 支持频率限制,在[频率限制](http://www.yiichina.com/doc/guide/2.0/rest-rate-limiting) 一节描述.
这些过滤器都在yii\rest\Controller::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 属性 为通过该控制器返回给用户的资源类名,该类必须继承yii\db\ActiveRecord.
### 自定义操作
yii\rest\ActiveController 默认提供一下操作:
*   yii\rest\IndexAction: 按页列出资源;
*   yii\rest\ViewAction: 返回指定资源的详情;
*   yii\rest\CreateAction: 创建新的资源;
*   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()"方法自定义数据provider 
    $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
    return $actions;
}
public function prepareDataProvider()
{
    // 为"index"操作准备和返回数据provider
}
~~~
请参考独立操作类的参考文档学习哪些配置项有用。
### 执行访问检查
通过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 
}
~~~
`checkAccess()` 方法默认会被yii\rest\ActiveController默认操作所调用,如果创建新的操作并想执行权限检查, 应在新的操作中明确调用该方法。
> 提示: 可使用[Role-Based Access Control (RBAC) 基于角色权限控制组件](http://www.yiichina.com/doc/guide/2.0/security-authorization)实现`checkAccess()`。
                    
        - 介绍(Introduction)
- 关于 Yii(About Yii)
- 从 Yii 1.1 升级(Upgrading from Version 1.1)
- 入门(Getting Started)
- 安装 Yii(Installing Yii)
- 运行应用(Running Applications)
- 第一次问候(Saying Hello)
- 使用 Forms(Working with Forms)
- 玩转 Databases(Working with Databases)
- 用 Gii 生成代码(Generating Code with Gii)
- 更上一层楼(Looking Ahead)
- 应用结构(Application Structure)
- 结构概述(Overview)
- 入口脚本(Entry Scripts)
- 应用(Applications)
- 应用组件(Application Components)
- 控制器(Controllers)
- 模型(Models)
- 视图(Views)
- 模块(Modules)
- 过滤器(Filters)
- 小部件(Widgets)
- 前端资源(Assets)
- 扩展(Extensions)
- 请求处理(Handling Requests)
- 运行概述(Overview)
- 引导(Bootstrapping)
- 路由引导与创建 URL(Routing and URL Creation)
- 请求(Requests)
- 响应(Responses)
- Sessions and Cookies
- 错误处理(Handling Errors)
- 日志(Logging)
- 关键概念(Key Concepts)
- 组件(Components)
- 属性(Properties)
- 事件(Events)
- 行为(Behaviors)
- 配置(Configurations)
- 别名(Aliases)
- 类自动加载(Class Autoloading)
- 服务定位器(Service Locator)
- 依赖注入容器(Dependency Injection Container)
- 配合数据库工作(Working with Databases)
- 数据库访问(Data Access Objects): 数据库连接、基本查询、事务和模式操作
- 查询生成器(Query Builder): 使用简单抽象层查询数据库
- 活动记录(Active Record): 活动记录对象关系映射(ORM),检索和操作记录、定义关联关系
- 数据库迁移(Migrations): 在团体开发中对你的数据库使用版本控制
- Sphinx
- Redis
- MongoDB
- ElasticSearch
- 接收用户数据(Getting Data from Users)
- 创建表单(Creating Forms)
- 输入验证(Validating Input)
- 文件上传(Uploading Files)
- 收集列表输入(Collecting Tabular Input)
- 多模型同时输入(Getting Data for Multiple Models)
- 显示数据(Displaying Data)
- 格式化输出数据(Data Formatting)
- 分页(Pagination)
- 排序(Sorting)
- 数据提供器(Data Providers)
- 数据小部件(Data Widgets)
- 操作客户端脚本(Working with Client Scripts)
- 主题(Theming)
- 安全(Security)
- 认证(Authentication)
- 授权(Authorization)
- 处理密码(Working with Passwords)
- 客户端认证(Auth Clients)
- 安全领域的最佳实践(Best Practices)
- 缓存(Caching)
- 概述(Overview)
- 数据缓存(Data Caching)
- 片段缓存(Fragment Caching)
- 分页缓存(Page Caching)
- HTTP 缓存(HTTP Caching)
- RESTful Web 服务
- 快速入门(Quick Start)
- 资源(Resources)
- 控制器(Controllers)
- 路由(Routing)
- 格式化响应(Response Formatting)
- 授权验证(Authentication)
- 速率限制(Rate Limiting)
- 版本化(Versioning)
- 错误处理(Error Handling)
- 开发工具(Development Tools)
- 调试工具栏和调试器(Debug Toolbar and Debugger)
- 使用 Gii 生成代码(Generating Code using Gii)
- TBD 生成 API 文档(Generating API Documentation)
- 测试(Testing)
- 概述(Overview)
- 搭建测试环境(Testing environment setup)
- 单元测试(Unit Tests)
- 功能测试(Functional Tests)
- 验收测试(Acceptance Tests)
- 测试夹具(Fixtures)
- 高级专题(Special Topics)
- 高级应用模版(Advanced Project Template)
- 从头构建自定义模版(Building Application from Scratch)
- 控制台命令(Console Commands)
- 核心验证器(Core Validators)
- 国际化(Internationalization)
- 收发邮件(Mailing)
- 性能优化(Performance Tuning)
- 共享主机环境(Shared Hosting Environment)
- 模板引擎(Template Engines)
- 集成第三方代码(Working with Third-Party Code)
- 小部件(Widgets)
- Bootstrap 小部件(Bootstrap Widgets)
- jQuery UI 小部件(jQuery UI Widgets)
- 助手类(Helpers)
- 助手一览(Overview)
- Array 助手(ArrayHelper)
- Html 助手(Html)
- Url 助手(Url)
