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

Create microservices using Yii2.0

angryTom
Release: 2019-11-01 18:13:56
forward
3971 people have browsed it

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
Copy after login

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"
        }
    ]
}
Copy after login

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:

<?php

// comment out the following two lines when deployed to production
defined(&#39;YII_DEBUG&#39;) or define(&#39;YII_DEBUG&#39;, true);
defined(&#39;YII_ENV&#39;) or define(&#39;YII_ENV&#39;, &#39;dev&#39;);

require(__DIR__ . &#39;/../vendor/autoload.php&#39;);
require(__DIR__ . &#39;/../vendor/yiisoft/yii2/Yii.php&#39;);

$config = require __DIR__ . &#39;/../config.php&#39;;
(new yii\web\Application($config))->run();
Copy after login

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

<?php
return [
    &#39;id&#39; => &#39;micro-app&#39;,

    //设置`micro-app`的根目录
    &#39;basePath&#39; => __DIR__,

    // 控制器所在目录。
    &#39;controllerNamespace&#39; => &#39;micro\controllers&#39;,

    // 设置命名空间为 micro
    &#39;aliases&#39; => [
        &#39;@micro&#39; => __DIR__,
    ],

    //默认访问地址
    &#39;defaultRoute&#39; => &#39;home/index&#39;,

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

        //Url 美化
        &#39;urlManager&#39; => [
            &#39;enablePrettyUrl&#39; => true,
            &#39;showScriptName&#39; => false,
            &#39;enableStrictParsing&#39; => false,
            &#39;rules&#39; => [
                &#39;<controller:\w+>/<action:\w+>/<id:\w+>&#39;   => &#39;<controller>/<action>&#39;,
            ],
        ],

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

];
Copy after login

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.

<?php
namespace micro\controllers\base;

use yii\web\Controller;

class BaseController extends Controller
{
    //关闭 csrf 验证
    public $enableCsrfValidation = false;
}
Copy after login

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

<?php

namespace micro\controllers;

use yii\web\Controller;

class HomeController extends BaseController
{
    public function actionIndex()
    {
        return &#39;欢迎来到 Yii2.0 微服务!&#39;;
    }
}
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:www.yii-china.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template