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:
<?php // comment out the following two lines when deployed to production 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'); $config = require __DIR__ . '/../config.php'; (new yii\web\Application($config))->run();
Also create a file called config.php which will contain all application configuration:
<?php return [ 'id' => 'micro-app', //設(shè)置`micro-app`的根目錄 'basePath' => __DIR__, // 控制器所在目錄。 'controllerNamespace' => 'micro\controllers', // 設(shè)置命名空間為 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' => [ '<controller:\w+>/<action:\w+>/<id:\w+>' => '<controller>/<action>', ], ], //數(shù)據(jù)庫配置 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=micro', 'username' => 'root', 'password' => '數(shù)據(jù)庫密碼', '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.
<?php namespace micro\controllers\base; use yii\web\Controller; class BaseController extends Controller { //關(guān)閉 csrf 驗證 public $enableCsrfValidation = false; }
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 '歡迎來到 Yii2.0 微服務(wù)!'; } }
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Create a distributed system using the Golang microservices framework: Install Golang, choose a microservices framework (such as Gin), create a Gin microservice, add endpoints to deploy the microservice, build and run the application, create an order and inventory microservice, use the endpoint to process orders and inventory Use messaging systems such as Kafka to connect microservices Use the sarama library to produce and consume order information

The Java framework supports horizontal expansion of microservices. Specific methods include: Spring Cloud provides Ribbon and Feign for server-side and client-side load balancing. NetflixOSS provides Eureka and Zuul to implement service discovery, load balancing and failover. Kubernetes simplifies horizontal scaling with autoscaling, health checks, and automatic restarts.

SpringBoot plays a crucial role in simplifying development and deployment in microservice architecture: providing annotation-based automatic configuration and handling common configuration tasks, such as database connections. Support verification of API contracts through contract testing, reducing destructive changes between services. Has production-ready features such as metric collection, monitoring, and health checks to facilitate managing microservices in production environments.

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

The steps to containerize and deploy Yii applications using Docker include: 1. Create a Dockerfile and define the image building process; 2. Use DockerCompose to launch Yii applications and MySQL database; 3. Optimize image size and performance. This involves not only specific technical operations, but also understanding the working principles and best practices of Dockerfile to ensure efficient and reliable deployment.

Migratingalaravel Projecttoyiiishallingbutachieffable WITHIEFLEFLANT.1) Mapoutlaravel component likeroutes, Controllers, Andmodels.2) Translatelaravel's SartisancommandeloequentTooyii's giiandetiverecordeba

The main difference between senior Yii developers and junior Yii developers is experience, depth of skills and way of thinking. 1. Senior developers pay attention to performance optimization and code reconstruction, and use Yii's cache mechanism to improve application performance. 2. They deeply understand Yii's underlying principles, participate in architectural design and technical decision-making, and use modular design to build flexible applications. 3. Senior developers pay attention to overall project planning and long-term development and play the role of mentor. Junior developers need to gradually improve through learning and practice, and eventually grow into senior developers.

When building a microservices architecture in a Java environment, consider the following middleware options: Apache Kafka: for stream processing and real-time applications; RabbitMQ: for asynchronous messaging; Apache Camel: for system integration; Hystrix: for improved fault tolerance and elasticity; SpringCloud: Provides tools and services for SpringBoot-based microservices.
