Yii2.0 实现API接口

来源:我的博客站 OceanicKang |《Yii2.0 实现API接口》

第一步

复制一份 backend 并且改名为 api,打开 config 里的 main.php ,将 id 修改为 app-id

第二步

1、修改 components 里的 user

'user' => [
    'identityClass' => 'common\models\member\Member',
    'enableAutoLogin' => true,
    'enableSession' => false,
],

2、在 components 里添加 response, 这串代码的用途是让 api 请求均为 200,其他 http 状态码会以 json
数据返回

举个例子:api 请求原本为 502 错误。但我加上这段配置以后,api 请求就会变成 200,不会报 502。但是 api
返回的 json 数据就会变成(当然,前提是你 api 返回规范就是 json 数据)

 {'error':502,'msg':'502 Bad Gateway','data':...}
'response' => [
    'class' => 'yii\web\Response',
    'on beforeSend' => function ($event) {
        $response = $event -> sender;
        $res_data = $response -> data;
        if ($response->data !== null && !isset($res_data['error'])) {
            $response -> data = [
                'error' => $res_data['status'],
                'msg' => $res_data['message'],
                'data' => [
                    'name' => $res_data['name'],
                    'code' => $res_data['code'],
                    'type' => $res_data['type'],
                ],
            ];
            $response -> statusCode = 200;
        }
    },
],

3、在 components 里添加 urlManager,这里就是你要配置的 api(写好API方法一定要在这里注册上去!!!)

'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'suffix' => '.html', // api后缀
    'rules' => [
	#################
	##  Order API  ##
        #################
        # http://域名/api/v1/order
        [
            'class' => 'yii\rest\UrlRule',
            'controller' => ['v1/order'],
            'pluralize'  => false, // 关闭复数模式
            'extraPatterns' => [
                'GET detail'       => 'detail', // 以GET请求 http://域名/api/v1/order/detail.html
            ]
        ],
    ]
],

第三步

编写基类控制器

controllers 里创建 AController.php


namespace api\controllers;

use Yii;
use yii\rest\ActiveController;
use yii\web\Response;
use yii\filters\auth\QueryParamAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\CompositeAuth;
use yii\filters\Cors;

class AController extends ActiveController
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        
        $behaviors['authenticator'] = [
                'class' => CompositeAuth::className(),
                'authMethods' => [
                        # 下面是三种验证access_token方式
                        //HttpBasicAuth::className(),
                        //HttpBearerAuth::className(),
                        # 这是GET参数验证的方式
                        # http://10.10.10.252:600/user/index/index?access-token=xxxxxxxxxxxxxxxxxxxx
                        QueryParamAuth::className(),
                ],
                // 写在optional里的方法不需要token验证
                'optional' => [],
        ];
	// 这个是跨域配置
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                // restrict access to
                'Access-Control-Request-Method' => ['POST', 'GET', 'DEL'],
                // Allow only POST and PUT methods
                'Access-Control-Request-Headers' => ['Origin', 'X-Requested-With', 'Content-Type', 'Accept'],
                // Allow only headers 'X-Wsse'
                'Access-Control-Allow-Credentials' => true,
                // Allow OPTIONS caching
                'Access-Control-Max-Age' => 3600,
                // Allow the X-Pagination-Current-Page header to be exposed to the browser.
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],
        ];
        

        # 定义返回格式是:JSON
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }
}

第四步

开始你的 api 工程吧!!!

我就先放上我的 Logout 退出登录给各位参考一下!


namespace api\modules\v1\controllers;

use Yii;
use api\modules\v1\controllers\AController;
use api\modules\v1\models\LoginForm;

class SiteController extends AController
{
    public $modelClass = 'api\modules\v1\models\Member';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        unset($behaviors['authenticator']['optional']); // 销毁基类的optional
        // 重写optional 不需要token验证的方法login
        $behaviors['authenticator']['optional'] = [
            'login',
        ];
        
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
	// 这一些都是Yii自带的RESTful API方法,我都给销毁了,因为...RESTful风格不太会,哈哈
        unset($actions['index']);  
        unset($actions['view']);
        unset($actions['create']);  
        unset($actions['update']);  
        unset($actions['delete']);

        return $actions;
    }

    /**
     * 退出登录
     */
    public function actionLogout()
    {
	    $msgdata = [
			'error' => 1,
			'msg' => '未知错误',
		];
        if((new LoginForm) -> logout()) {
            $msgdata = [
                'error' => 0,
                'msg' => '退出成功',
            ];
        }else {
            $msgdata['msg'] = '退出失败';
        }

        return $msgdata; // 因为基类有配置过返回格式转换为 json,所以直接 return 不搭嘎
        // 当然也可以自己 json_encode 一下
    }
}

小生这厢有礼了(๑´ڡ`๑)

你可能感兴趣的:(YII2.0)