Home >Backend Development >PHP Tutorial >PHP and Lumen integrate to realize microservice architecture development
With the rapid development of IT technology, modern enterprises are facing more and more complex business systems. The traditional single application architecture can no longer meet the needs, and the microservice architecture emerged as the times require. Microservice architecture is an architectural style in which applications are composed of multiple small services that can be deployed, run, expanded, and maintained independently to achieve better scalability, reusability, and flexibility. sex.
So, how to use PHP to implement microservice architecture? The answer is to use Lumen - a lightweight PHP framework. Based on Laravel, Lumen is a PHP framework designed for building microservices and APIs. This article will introduce how to integrate microservice architecture in Lumen framework.
First, we need to install the Lumen framework locally. The installation steps are the same as for Laravel. It can be installed through composer, as shown below:
composer create-project --prefer-dist laravel/lumen lumen_api
After completion, we can start the Lumen framework running environment locally:
php -S localhost:8000 -t public
When "Lumen development server started: e11336deb115203d688c169b7dfb1d1b", it means that the Lumen framework has successfully deployed the local running environment, and we can access its default page through http://localhost:8000.
Next, we will use the Lumen framework to write our first microservice. We are going to create a simple API that gets a list of all users. The steps to implement this API are as follows:
In the routing file routes/web.php, we need to write a route to handle requests to the API. In this example, we will write a GET route in the route file to handle /get_users requests, as shown below:
$router->get('/get_users', function () use ($router) { return 'List of all users'; });
At this point, when you request http://localhost:8000/get_users, The string "List of all users" will be returned.
Now, we need to create a controller class for our API. Let's create the UserController class that will be responsible for handling the get_users request and returning the list of users. We can create the UserController.php file in the app/Http/Controllers directory and copy the following code into it:
<?php namespace AppHttpControllers; use IlluminateHttpRequest; class UserController extends Controller { public function getAllUsers() { $users = ['User 1', 'User 2', 'User 3']; return response()->json($users); } }
In the above code, we define a public function getAllUsers(), which will Returns a list of all users as a JSON formatted response.
Now we need to register the API routing to the UserController controller in the routing file and map our route /api/get_users to the method UserController@getAllUsers, and modify the route file as follows:
$router->get('api/get_users', 'UserController@getAllUsers');
At this time, when you request http://localhost:8000/api/get_users, a user list in JSON format will be returned, as shown below :
{ "0": "User 1", "1": "User 2", "2": "User 3" }
Finally, we also need to import the UserController class at the top, as shown below:
<?php use AppHttpControllersUserController;
In this way, we have successfully implemented a most basic API, and it can be used under the Lumen framework run.
Before this, we have created our first API in the Lumen framework, but it is not a real microservice application. In order to turn Lumen into a microservice architecture application, we need to use DDD domain model design ideas to rebuild our application. Then, we will use the idea of microservices to decompose each of our services into microservices.
First, we need to define our domain model, which is the core of our application. In this example, we will create a simple user management microservice whose main function is to manage user data.
Our user management microservice must have the following functions:
Now we need to map these functions to the interface of the microservice.
We will design different microservice interfaces according to different functions in the domain model. Here we will define the following microservice interface:
Now, we need to divide our microservice interface into different microservices in the service module. In this example, we will use the following three microservice modules:
These microservice modules will interact directly with our database.
We now have our domain model, microservice interface and microservice module components, and we can now simply combine them into A microservices architecture. The entire architecture looks like this:
API Gateway (Lumen) <--> User Authentication and Authorization Microservice <--> User Information Management Microservice <--> User Registration Microservice
We enable the Lumen API Gateway, which is the initial point of our system and will receive all requests and route them to the appropriate microservice module. Our domain model is our business logic, and the microservice interface will control our data interactions.
现在,我们已经设计了微服务模块、微服务接口和整体微服务架构,我们可以开始实现我们的微服务。我们将针对上述三个微服务模块分别进行介绍。
我们的用户认证与授权微服务负责处理所有与用户认证相关的任务。它将接收用户凭据并验证它们的凭证是否正确。如果验证成功,它将生成一个JWT标记并将其返回给用户。
我们将针对以下任务编写用户认证与授权微服务:
我们可以通过安装tymon / jwt-auth组件来编写我们的用户认证与授权微服务。使用以下命令进行安装:
composer require tymon/jwt-auth
然后,我们需要在配置文件中配置JWT密钥。现在,我们可以使用以下代码为用户认证与授权微服务创建一个新控制器:
<?php namespace AppHttpControllers; use IlluminateSupportFacadesAuth; use AppModelsUser; use IlluminateHttpRequest; class AuthController extends Controller { /** * Create a new AuthController instance. * * @return void */ public function __construct() { $this->middleware('auth:api', ['except' => ['login']]); } /** * Get a JWT token. * * @return void */ public function login(Request $request) { $credentials = $request->only('email', 'password'); if ($token = $this->guard()->attempt($credentials)) { return $this->respondWithToken($token); } return response()->json(['error' => 'Unauthorized'], 401); } /** * Get the authenticated User. * * @return void */ public function me() { return response()->json(auth()->user()); } /** * Log the user out (Invalidate the token). * * @return void */ public function logout() { auth()->logout(); return response()->json(['message' => 'Successfully logged out']); } /** * Refresh a token. * * @return void */ public function refresh() { return $this->respondWithToken(auth()->refresh()); } /** * Get the token array structure. * * @param string $token * * @return mixed */ protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } /** * Get the guard to be used during authentication. * * @return IlluminateContractsAuthGuard */ public function guard() { return Auth::guard(); } }
用户信息管理微服务将负责向用户提供用户相关信息。在本例中,我们将创建以下操作的API:
首先,我们将创建一个新控制器来管理用户信息:
<?php namespace AppHttpControllers; use IlluminateSupportFacadesHash; use AppModelsUser; use IlluminateHttpRequest; class UserController extends Controller { public function getUser(Request $request) { $user = User::where('id', $request->id)->first(); if (!$user) { return response()->json(['message' => 'User not found.'], 404); } return response()->json(['user' => $user]); } public function updateUserPassword(Request $request) { $user = User::where('id', $request->id)->first(); if (!$user) { return response()->json(['message' => 'User not found.'], 404); } $user->password = Hash::make($request->password); $user->save(); return response()->json(['message' => 'User password updated successfully.']); } }
注册微服务将处理用户注册过程。在本例中,我们将创建以下功能:
首先,我们将创建一个新控制器来处理用户注册。它应该读取POST有效载荷并保存新用户到数据库中。然后,它应该生成用户验证令牌并将其发送到用户的电子邮件地址。
<?php namespace AppHttpControllers; use IlluminateSupportFacadesHash; use AppModelsUser; use IlluminateHttpRequest; class RegisterController extends Controller { public function create(Request $request) { $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); $user->sendEmailVerificationNotification(); // send verification email return response()->json(['message' => 'User created successfully.']); } }
现在,我们可以在Lumen框架中实现我们的微服务。我们的系统现在有三个微服务模块:“用户认证和授权微服务”、“用户信息管理微服务”和“用户注册微服务”,这些微服务与数据库交互,并由Lumen API Gateway处理。
本文介绍了如何在Lumen框架中集成微服务架构,包括领域模型设计、微服务接口和微服务模块的开发。以上代码展示了Lumen框架如何开发微服务的过程。通过使用Lumen框架,开发者可以快速构建微服务,提高代码质量,加快项目进程。
The above is the detailed content of PHP and Lumen integrate to realize microservice architecture development. For more information, please follow other related articles on the PHP Chinese website!