Home  >  Article  >  PHP Framework  >  Create microservices using Yii2.0

Create microservices using Yii2.0

angryTom
angryTomforward
2019-11-01 16:15:123571browse

Create microservices using Yii2.0

Concept


Split a large single application and service into several or even dozens Each supports microservices, which scales individual components rather than the entire application stack to meet service level agreements.

The traditional development model is to put all functions in one package, with basically no dependencies. The advantages of this are simple development, centralized management, functions are all local, and there is no distributed management and scheduling. consumption. But the shortcomings are also obvious: low efficiency, developers all change code in the same project, waiting for each other, and conflicts continue. Poor stability, a small problem may cause the entire application to hang up. In addition, there are obvious disadvantages in resource utilization. For example, in the e-commerce Double 11 promotion scenario, the pressure to place an order is very high and the pressure to evaluate is relatively small. So we hope to temporarily increase the allocation to cope with the large process of Double 11, and we can only increase all the resources. allocation, rather than just adding additional allocations to order services at a fixed point. Therefore, the microservice architecture has gradually become popular and applied to large website platforms.

Recommended: "Yii2.0 Framework Introduction and Practical Project Development Video Tutorial"

So introduce today’s topic, how to do microservices in Yii ? Yii can be used easily without the features included in the basic and advanced templates. In other words, Yii is already a micro-framework. The directory structure provided by the template is not required to work with Yii.

Installing Yii


Create a directory for your project and change the working directory to that path. The commands used in the examples are Unix-based, but similar commands exist in Windows.

mkdir micro-app
cd micro-app

Note: Some Composer knowledge is required to proceed. If you don't know how to use composer yet, take some time to read the Composer guide.

Use your favorite editor to create a composer.json file in the micro-app directory and add the following content:

{
    "require": {
        "yiisoft/yii2": "~2.0.0"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://asset-packagist.org"
        }
    ]
}

Save the file and run composer install Order. This will install the framework and all its dependencies.

Create project structure


After installing the framework, you need to create an entry point for this application. The entry point is the first file that will be executed when you try to open the application. For security reasons, it is recommended to place the entry point file in a separate directory and set it to the web root.

Create a web directory and place index.php in it with the following content:

run();

Also create a file called config.php which will contain all application configuration:

 'micro-app',

    //设置`micro-app`的根目录
    'basePath' => __DIR__,

    // 控制器所在目录。
    'controllerNamespace' => 'micro\controllers',

    // 设置命名空间为 micro
    'aliases' => [
        '@micro' => __DIR__,
    ],

    //默认访问地址
    'defaultRoute' => 'home/index',

    'components' => [
        //请求配置
        'request' => [
            'cookieValidationKey' => 'test&123456',
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],

        //Url 美化
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => false,
            'rules' => [
                '//'   => '/',
            ],
        ],

        //数据库配置
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=micro',
            'username' => 'root',
            'password' => '数据库密码',
            'charset' => 'utf8',
        ],
    ],

];

Info: Although the configuration can be saved in the index.php file, it is recommended to use it separately. This way it can also be used in console applications as shown below.

Your project is now ready for coding. Although it's up to you to decide the project directory structure, as long as you respect namespaces.

Create the first controller


Before creating the controller, create a controllers/base directory and create a base controller BaseController.

Then create a new SiteController.php under the controller folder. This is the default controller that will handle requests without path information.

If you want to use a different name for this controller, you can configure yii\base\Application::$defaultRoute to change it. For example, for HomeController it would be 'defaultRoute' => 'home/index'.

At this point, the project structure should look like this:

micro-app/
├── composer.json
├── config.php
├── web/
    └── index.php
└── controllers/
    └── base
        └── BaseController.php
    └── HomeController.php
└── vendor

If you haven't set up a web server yet, you may want to check out the sample web server configuration file. Another option is to use the yii serve command, which will use the PHP built-in web server. You can run it from the micro-app/ directory by:

vendor/bin/yii serve --docroot=./web

Opening the application URL in a browser should now print out "Welcome to Yii2.0 Microservices!", which is already in the HomeController: Returned in :actionIndex().

Info: In our example we have changed the default application namespace app to micro to indicate that you are not limited by this name (if that is what you think) and then adjust the controllers namespace and set the correct alias.

The above is the detailed content of Create microservices using Yii2.0. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:www.yii-china.com. If there is any infringement, please contact admin@php.cn delete