yii2配置api模块

本文介绍了如何在Yii2项目中配置API模块,包括创建目录、编辑配置文件、添加控制器和路由,以及重启nginx服务。通过这些步骤,成功设置后,可以通过访问特定接口进行业务接口的开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在项目下添加目录weChatApi
2、在common/config/bootstrap.php文件添加一行代码:
Yii::setAlias( '@weChatApi' , dirname( dirname( __DIR__ ) ) . '/weChatApi' );
3、在weChatApi里面创建如下目录:
在这里插入图片描述
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

<?php

namespace weChatApi\base\controllers;

use yii\filters\auth\HttpBasicAuth;
use yii\rest\ActiveController;
use Yii;

/**
 * restful api 底层控制器
 * Class ApiController
 * @package weChatApi\base\controllers
 */
class ApiController extends ActiveController
{

    /**
     * 操作成功标示码
     */
    const ACTION_SUCCESS_CODE = 1;

    /**
     * 操作失败标示码
     */
    const ACTION_FAIL_CODE = 0;

    /**
     * 开发的权限
     * @var array
     */
    private $allowedApis = [
        'user/login' ,
    ];

    /**
     * 关闭csrf验证
     * @var bool
     */
    public $enableCsrfValidation = false;

    /**
     * 验证授权
     *
     * @param array $optional
     *
     * @return array
     */
    public function behaviors( $optional = [] )
    {
        $behaviors = parent::behaviors();
        $behaviors[ 'authenticator' ] = [
            'class' => 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

<?php

main.php

<?php
$params = array_merge(
    require __DIR__ . '/../../common/config/params.php' ,
    require __DIR__ . '/../../common/config/params-local.php' ,
    require __DIR__ . '/params.php'
);
return [
    'id' => '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

<?php
return [];

PublicController.php

<?php

namespace weChatApi\controllers;

use weChatApi\base\controllers\ApiController;

/**
 * 公共控制器
 * Class PublicController
 * @package adminApi\controllers
 */
class PublicController extends ApiController
{

    /**
     * 默认方法
     * @return array
     */
    public function actionIndex()
    {
        return $this->success();
    }
}

UserController.php

<?php

namespace weChatApi\modules\v1\controllers;

use weChatApi\base\controllers\ApiController;

/**
 * 用户控制器
 * Class UserController
 * @package weChatApi\modules\v1\controllers
 */
class UserController extends ApiController
{

    /**
     * 指定ORM模型
     * @var string
     */
    public $modelClass = '';

    /**
     * 登录
     * @return array
     */
    public function actionLogin()
    {
        return $this->success();
    }
}

Module.php

<?php

namespace weChatApi\modules\v1;

/**
 * weChatApi v1 模块
 *
 * Class Module
 * @package weChatApi\modules\v1
 */
class Module extends \yii\base\Module
{

    /**
     * 指定命名控制器
     * @var string
     */
    public $controllerNamespace = 'weChatApi\modules\v1\controllers';

    /**
     * 初始化
     */
    public function init()
    {
        parent::init();
    }
}

index.php

<?php
defined( 'YII_DEBUG' ) or define( 'YII_DEBUG' , true );
defined( 'YII_ENV' ) or define( 'YII_ENV' , 'dev' );
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../../common/config/bootstrap.php';
require __DIR__ . '/../config/bootstrap.php';
$config = yii\helpers\ArrayHelper::merge(
    require __DIR__ . '/../../common/config/main.php' ,
    require __DIR__ . '/../../common/config/main-local.php' ,
    require __DIR__ . '/../config/main.php'
);
( new yii\web\Application( $config ) )->run();

Authentication.php

<?php

namespace weChatApi;

use common\activeRecords\Admin;
use yii\web\IdentityInterface;

/**
 * 实现user组件
 * Class Authentication
 * @package adminApi\modules\v1
 */
class Authentication extends Admin implements IdentityInterface
{

    /**
     * @param int|string $id
     *
     * @return Authentication|IdentityInterface|null
     */
    public static function findIdentity( $id )
    {
        return static::findOne( [ 'id' => $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": []
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值