Yii2构建RESTFull接口

2022-10-24  本文已影响0人  itBox

项目中用到了小程序调用RESTFull接口,故用Yii2快速实现一套RESTFull接口,需要的小伙伴直接拿走。

直接上代码:

<?php
namespace app\modules\api\controllers;

use yii\rest\ActiveController;
use \yii\base\DynamicModel;

class ApiBaseController extends ActiveController {
    public function beforeAction($action)
    {
       return \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    }

    //支持 filter 检索
    public function actions()
    {
        $actions = parent::actions();
        $actions['index']['dataFilter'] = [
            'class' => \yii\data\ActiveDataFilter::class,
            'attributeMap' => [
                'clockIn' => 'clock_in',
            ],
            'searchModel' => (new DynamicModel(['id', 'age_id', 'cat_id', 'topic_id', 'member_id', 'book_id','status','clockIn']))
                ->addRule(['id', 'age_id', 'cat_id', 'topic_id', 'member_id', 'book_id'], 'integer', ['min' => 1])
                ->addRule(['title'], 'string', ['min' => 2, 'max' => 200])
                ->addRule(['status', 'clockIn'], 'integer')
                // ->addRule(['status', 'clockIn'], 'string')
                ,
        ];
        
        return $actions;
    }
    protected function renderJSON($data=[], $msg ="ok", $code = 200)
    {
        return [
            "code" => $code,
            "msg"   =>  $msg,
            "data"  =>  $data,
            "req_id" =>  uniqid()
        ];
        // 因 beforeAction 中定义了 response->format = FORMAT_JSON
        //这个直接 return [] 就是返回 JSON 数据
        header('Content-type: application/json');
        echo json_encode([
            "code" => $code,
            "msg"   =>  $msg,
            "data"  =>  $data,
            "req_id" =>  uniqid()
        ]);
        return \Yii::$app->end();
    }
    public function post($key, $default = "") {
        return \Yii::$app->request->post($key, $default);
    }

    public function get($key, $default = "") {
        return \Yii::$app->request->get($key, $default);
    }
}

说明:
重写父类 actions() 方法,实现对 filter 关键词检索的支持,这里有空可以多研究一下。

renderJSON 方法:因 beforeAction 中定义了 response->format = FORMAT_JSON
这个直接 return [] 就是返回 JSON 数据

上一篇 下一篇

猜你喜欢

热点阅读