标签 微服务 下的文章

学习Yii2微服务框架 实现一些基本功能 及案例

   'id' => 'micro-app',
    // the basePath of the application will be the `micro-app` directory
    'basePath' => __DIR__,
    // this is where the application will find all controllers
    'controllerNamespace' => 'micro\controllers',
    // set an alias to enable autoloading of classes from the 'micro' namespace
    'aliases' => [
        '@micro' => __DIR__,
    ],
    'language' => 'zh-CN',
    'components' => [
        //获取JSON数据
        'request' => [
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
        //配置自定义响应
        'response' => [
            'class' => 'yii\web\Response',
            'on beforeSend' => function ($event) {
                    $response = $event->sender;
                    $code = $response->getStatusCode();
                    $msg = $response->statusText;
                    if ($code == 404) {
                        !empty($response->data['message']) && $msg = $response->data['message'];
                    }
                    //设置固定返回数据参数
                    $data = [
                        'code' => $code,
                        'msg' => $msg,
                        'data' => $response->data
                    ];
                    $code == 200 && $data['data'] = $response->data;
                    $response->data = $data;
                    $response->format = yii\web\Response::FORMAT_JSON;
            },
        ],
        //会员
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
            'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
        ],
        //URL美化
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
               '' => 'site/index',
               ['class' => 'yii\rest\UrlRule', 'controller' => 'post','pluralize'=>false],
                
            ],
        ],
        //连接MYSQL数据库
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=micro',
            'username' => 'root',
            'password' => 'root',
            'charset' => 'utf8',
        ],
        'cookieValidationKey' => 'O1d232trde1xww-M97_7QvwPo-5QGdkLMp#@#@', 
    ],

以下为DEMO
micro-app.zip