yii2配置api模块

1、在项目下添加目录weChatApi
2、在common/config/bootstrap.php文件添加一行代码:
Yii::setAlias( '@weChatApi' , dirname( dirname( __DIR__ ) ) . '/weChatApi' );
3、在weChatApi里面创建如下目录:
yii2配置api模块_第1张图片
4、修改/etc/nginx/conf.d/default.conf添加如下代码:

    location /BlackCard/weChatApi/web/ {
        index  index.html index.htm index.php;
        try_files $uri $uri/ /BlackCard/weChatApi/web/index.php?$query_string;
    }

重启nginx服务:systemctl reload nginx
5、在weChatApi添加目录:runtime,命令如下:

mkdir runtime
chmod 777 runtime

6、各个文件的代码如下:
ApiController.php

 HttpBasicAuth::className() ,
        ];
        return $behaviors;
    }

    /**
     * 重写
     *
     * @param $action
     *
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction( $action )
    {
        if ( $this->isAllowedApi() ) {
            return true;
        }
        parent::beforeAction( $action );
        return true;
    }

    /**
     * 注销自带的 rest
     * @return array
     */
    public function actions()
    {
        $actions = parent::actions();
        unset(
            $actions[ 'index' ] ,
            $actions[ 'update' ] ,
            $actions[ 'create' ] ,
            $actions[ 'delete' ]
        );
        return $actions;
    }

    /**
     * 验证是否是开发的接口请求
     * @return bool
     */
    private function isAllowedApi()
    {
        $controllerId = Yii::$app->controller->id;
        $action = Yii::$app->controller->action->id;
        $requestApi = $controllerId . '/' . $action;
        return in_array( $requestApi , $this->allowedApis );
    }

    /**
     * 操作成功
     *
     * @param array  $data
     * @param int    $count
     * @param string $msg
     *
     * @return array
     */
    public function success( $data = [] , $count = 0 , $msg = '操作成功' )
    {
        return [
            'code' => self::ACTION_SUCCESS_CODE ,
            'message' => $msg ,
            'count' => $count ,
            'data' => $data ,
        ];
    }

    /**
     * 操作失败
     *
     * @param string $msg
     * @param array  $data
     * @param int    $count
     *
     * @return array
     */
    public function fail( $msg = '操作失败' , $data = [] , $count = 0 )
    {
        return [
            'code' => self::ACTION_FAIL_CODE ,
            'message' => $msg ,
            'count' => $count ,
            'data' => $data ,
        ];
    }
}

bootstrap.php

main.php

 'app-weChatApi' ,
    'basePath' => dirname( __DIR__ ) ,
    'language' => 'zh-CN' ,
    'controllerNamespace' => 'weChatApi\controllers' ,
    'bootstrap' => [ 'log' ] ,
    'timeZone' => 'Asia/Shanghai' ,
    'modules' => [
        'v1' => [
            'class' => 'weChatApi\modules\v1\Module' ,
        ] ,
    ] ,
    'components' => [
        'response' => [
            'class' => 'yii\web\Response' ,
            'on beforeSend' => function ( $event ) {
                $response = $event->sender;
                $response->format = \yii\web\Response::FORMAT_JSON;
                $statusCode = $response->statusCode;
                switch ( $statusCode ) {
                    case 200 :
                        $returnData = $response->data;
                        break;
                    case 401 :
                        $returnData = [
                            'code' => 401 ,
                            'message' => '没有权限' ,
                            'count' => 0 ,
                            'data' => [] ,
                        ];
                        break;
                    case 404 :
                        $returnData = [
                            'code' => 0 ,
                            'message' => '接口不存在' ,
                            'count' => 0 ,
                            'data' => [] ,
                        ];
                        break;
                    default:
                        $returnData = [
                            'code' => 0 ,
                            'message' => '500错误' ,
                            'count' => 0 ,
                            'data' => [] ,
                        ];
                        break;
                }
                $response->data = $returnData;
                $response->statusCode = 200;
            } ,
        ] ,
        'request' => [
            'csrfParam' => '_csrf-backend' ,
            'cookieValidationKey' => 's2LK6wSyyrvMAyJUHBOJn2RRrThtIQ7E' ,
        ] ,
        'user' => [
            'identityClass' => 'weChatApi\Authentication' ,
            'enableAutoLogin' => false ,
            'enableSession' => false ,
            'loginUrl' => null ,
            //'identityCookie' => [ 'name' => '_identity-adminApi' , 'httpOnly' => true ] ,
        ] ,
        'session' => [
            // this is the name of the session cookie used for login on the backend
            'name' => 'BlackCard-weChatApi' ,
        ] ,
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0 ,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget' ,
                    'levels' => [ 'error' , 'warning' ] ,
                ] ,
            ] ,
        ] ,
        'urlManager' => [
            'enablePrettyUrl' => true ,
            'showScriptName' => false ,
            'enableStrictParsing' => true ,
            'rules' => [
                [
                    'pluralize' => false ,
                    'class' => 'yii\rest\UrlRule' ,
                    'controller' => [ 'public' ] ,
                    'extraPatterns' => [
                        'GET index' => 'index' ,
                    ] ,
                ] ,
                //测试模块
                [
                    'pluralize' => false ,
                    'class' => 'yii\rest\UrlRule' ,
                    'controller' => [ 'v1/user' ] ,
                    'extraPatterns' => [
                        'POST login' => 'login',
                    ] ,
                ] ,
            ] ,
        ] ,
    ] ,
    'params' => $params ,
];

params.php

PublicController.php

success();
    }
}

UserController.php

success();
    }
}

Module.php

index.php

run();

Authentication.php

 $id ] );
    }

    /**
     * @param mixed $token
     * @param null  $type
     *
     * @return void|IdentityInterface
     */
    public static function findIdentityByAccessToken( $token , $type = null )
    {
        return self::findOne( [ 'auth_key' => $token ] );
    }

    /**
     * @return int|mixed|string
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @return string
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @param string $authKey
     *
     * @return bool
     */
    public function validateAuthKey( $authKey )
    {
        return $this->getAuthKey() === $authKey;
    }
}

7、访问接口地址:/BlackCard/weChatApi/web/v1/user/login
返回:

{
    "code": 1,
    "message": "操作成功",
    "count": 0,
    "data": []
}

说明配置成功。可以开发业务接口了

你可能感兴趣的:(php,yii2)