Home  >  Article  >  Backend Development  >  Best Practices for PHP Hyperf Microservice Development: From Prototype to Production

Best Practices for PHP Hyperf Microservice Development: From Prototype to Production

WBOY
WBOYOriginal
2023-09-12 10:36:11795browse

PHP Hyperf微服务开发最佳实践:从原型到生产环境

PHP Hyperf is a high-performance microservice framework that is widely used in the development of large Internet companies. This article will introduce best practices for microservice development using PHP Hyperf, from prototype to production environment.

1. Environment preparation

Before you start using PHP Hyperf for microservice development, you need to prepare the environment. First, make sure that the PHP operating environment has been installed and the version is 7.2 or above. Secondly, install Composer to manage PHP dependency packages. Finally, install Hyperf’s command line tool hyperf/hyperf.

2. Create a project

Use Hyperf’s command line tool to create a new project:

$ composer create-project hyperf/hyperf-skeleton

This command will create a project named hyperf-skeleton in the current directory . Enter the project directory:

$ cd hyperf-skeleton

3. Develop a prototype

Before starting formal development, create a prototype to verify some basic functions. You can first create a UserController and add a registration interface:

<?php

namespace AppController;

use HyperfHttpServerAnnotationController;
use HyperfHttpServerAnnotationPostMapping;

/**
 * @Controller(prefix="/user")
 */
class UserController
{
    /**
     * @PostMapping("/register")
     */
    public function register()
    {
        // 注册逻辑
    }
}

Then, register the interface in the routing configuration file (routes.php):

use AppControllerUserController;

Router::addGroup('/user', function () {
    Router::post('/register', [UserController::class, 'register']);
});

Start the Hyperf development server:

$ php bin/hyperf.php start

Use a tool such as Postman to send a POST request to http://127.0.0.1:9501/user/register, and you can see that the interface works normally.

4. Database Operation

In real microservice development, it is often necessary to interact with the database. Hyperf provides the Hyperf/Database component to operate the database. First, install the Hyperf/Database component through Composer:

$ composer require hyperf/database

Then, configure the database connection information in the .env file:

DB_DRIVER=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=

Next, configure the database in the config/autoload/databases.php file Connection information:

return [
    'default' => [
        'driver' => env('DB_DRIVER', 'mysql'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', 3306),
        'database' => env('DB_DATABASE', 'test'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
    ],
];

Then, use the Hyperf/Database component in UserController to perform database operations:

<?php

namespace AppController;

use HyperfDbConnectionDb;
use HyperfHttpServerAnnotationController;
use HyperfHttpServerAnnotationPostMapping;

/**
 * @Controller(prefix="/user")
 */
class UserController
{
    /**
     * @PostMapping("/register")
     */
    public function register()
    {
        $username = $this->request->input('username');
        $password = $this->request->input('password');

        // 插入用户数据
        $userId = Db::table('users')->insertGetId([
            'username' => $username,
            'password' => $password,
        ]);

        // 返回用户ID
        return $this->response->json(['user_id' => $userId]);
    }
}

5. Security measures

In microservice development, security is very important. Hyperf provides several security measures to protect applications. Hyperf/Security components can be used to encrypt and decrypt sensitive data, as well as generate and verify signatures.

Install the Hyperf/Security component:

$ composer require hyperf/security

Configure the Hyperf/Security component in the config/autoload/dependencies.php file:

return [
    'dependencies' => [
        // ...
        HyperfSecurityEncrypterInterface::class => HyperfSecurityHashPasswordHash::class,
        HyperfSecuritySecurityManagerInterface::class => HyperfSecuritySecurityManager::class,
    ],
];

Then, use Hyperf/ in UserController Security component to encrypt and decrypt data:

<?php

namespace AppController;

use HyperfDbConnectionDb;
use HyperfHttpServerAnnotationController;
use HyperfHttpServerAnnotationPostMapping;
use HyperfSecurityEncrypterInterface;
use HyperfSecuritySecurityManagerInterface;

/**
 * @Controller(prefix="/user")
 */
class UserController
{
    /**
     * @PostMapping("/register")
     */
    public function register(EncrypterInterface $encrypter, SecurityManagerInterface $security)
    {
        $username = $this->request->input('username');
        $password = $this->request->input('password');

        // 加密密码
        $hashedPassword = $security->passwordHash($password);

        // 插入用户数据
        $userId = Db::table('users')->insertGetId([
            'username' => $username,
            'password' => $hashedPassword,
        ]);

        // 使用加密算法生成令牌
        $token = $encrypter->encrypt([
            'user_id' => $userId,
            'username' => $username,
        ]);

        // 返回用户ID和令牌
        return $this->response->json(['user_id' => $userId, 'token' => $token]);
    }
}

6. Production environment deployment

When the development is completed, the project can be deployed to the production environment. Hyperf provides some convenient commands for deployment, such as the following command to generate a routing cache:

$ php bin/hyperf.php vendor:publish hyperf/snowflake

The configuration can be reloaded through the following command:

$ php bin/hyperf.php vendor:publish hyperf/config

Finally, use the following command to start the production environment server :

$ php bin/hyperf.php start

This completes a best practice for PHP Hyperf microservice development from prototype to production environment. I hope this article can be helpful to beginners and can play a role in microservice development.

The above is the detailed content of Best Practices for PHP Hyperf Microservice Development: From Prototype to Production. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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