PHPackages                             leegoway/yii2-rest - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. leegoway/yii2-rest

ActiveYii2-extension[Framework](/categories/framework)

leegoway/yii2-rest
==================

The Yii2 Rest extension for the Yii framework

125PHP

Since Nov 8Pushed 9y ago1 watchersCompare

[ Source](https://github.com/leegoway/yii2-rest)[ Packagist](https://packagist.org/packages/leegoway/yii2-rest)[ RSS](/packages/leegoway-yii2-rest/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

The Yii2 Rest extension for the Yii framework
=============================================

[](#the-yii2-rest-extension-for-the-yii-framework)

The Yii2 Rest extension for the Yii framework

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist leegoway/yii2-rest "*"

```

or add

```
"leegoway/yii2-rest": "*"

```

to the require section of your `composer.json` file.

Usage
-----

[](#usage)

#### 格式化的ActiveController输出

[](#格式化的activecontroller输出)

Once the extension is installed, simply use it in your controller as base controller by :

```

```

then you can get formatted output like : {"code":200, "msg":"", "data":{...}}

#### 主动使用格式化类进行格式化输出

[](#主动使用格式化类进行格式化输出)

Besides, use the formatter class anywhere you need like this :

```
use leegoway\rest\Formatter;

...
Formatter::success($data);//返回业务数据
Formatter::error($errors);//返回校验失败的数据
Formatter::fail($msg);//业务逻辑问题导致的失败
```

then you can get formatted output.

#### 捕获业务异常

[](#捕获业务异常)

Last，you can use following method to catch your defined exception and output formatted response.

###### a、modify your config file

[](#amodify-your-config-file)

```
'errorHandler' => [
    'class' => 'leegoway\rest\RestErrorHandler',
    'errorAction' => 'site/error',
    'restErrorAction' => 'error/error'
],
```

###### b、modify your `error/error` controller

[](#bmodify-your-errorerror-controller)

```
