Over the past year and a half, Hyperf 2.2 has released a total of 35 minor version, bringing Hyperf to a前所未有的高度got some nice data feedback here too.

Hyperf in GitHub with Gitee The degree of attention on the Internet has also been significantly improved, and they have won 4.9k with 791 indivual starthe overall attention growth is also very stable.

The installed base of the Hyperf framework also reached 90万次every day about 1300次installation, which also shows that Hyperf has广泛应用In related industries and supports a large number of system operations.

The effective repo under the Hyperf organization has reached about 140个(After removing the Archive project), the maintenance workload is unprecedentedly huge, but iterations are still frequent.

Thanks to all members of the Hyperf team for their hard work and contributions, and also to all PR contributors. Without your participation, there would be no Hyperf today.

Thanks ALL Contributors

Hyperf 3.0 New Era

Hyperf 3.0 brings many very interesting new capabilities, some of which are in the PHP field前所未有Of course, these new capabilities cannot be separated from the active development of other open source communities, including but not limited to PHP,Swoole,Swow,PHPMicro,DTM,Seata Waiting for the open source community, I also sincerely hope that everyone can contribute to these open source communities in their spare time, building a better future together.

Native annotations (Attribute)

With the release of PHP 8.1 and 8.2, many new features have been brought to PHP, among which the most related to Hyperf is PHP’s原生注解(Attribute)Yes, Hyperf 3.0 also abandons the annotation function implementation based on annotation parsing used in the past, and uses PHP’s native annotations instead. Of course, the corresponding PHP version that depends on it will also be adjusted to the minimum requirement of PHP 8.0.

We use the simplest Controller case to present the use of new native annotations:


namespace App\\Controller;

use Hyperf\\HttpServer\\Contract\\RequestInterface;
use Hyperf\\HttpServer\\Annotation\\Controller;
use Hyperf\\HttpServer\\Annotation\\RequestMapping;

class IndexController
    // Hyperf 会自动为此方法生成一个 /index/index 的路由,允许通过 GET 或 POST 方式请求
    #[RequestMapping(path: "index", methods: "get,post")]
    public function index(RequestInterface $request)
        // 从请求中获得 id 参数
        $id = $request->input('id', 1);
        return (string)$id;

At the same time, with the application of native annotations, it is also possible to support repeated application of the same annotation at the same position in 3.0. For example, in the past, when a Controller Action wanted to apply multiple Middleware, it needed to pass @Middlewares The annotation contains multiple @Middleware Annotations implement application, while in 3.0 you can directly write multiple @Middleware Annotations implement the application. At the same time, in 3.0, annotations can also be applied to method parameters to implement functions such as method parameter definition and parameter analysis.

Adjust from annotation annotations to native annotations, and there is no need to worry about the workload of migration and transformation of previous projects. Hyperf also provides corresponding tools for one-click automatic conversion, which only needs to be introduced in 2.2 hyperf/code-generator components, and execute php bin/hyperf.php code:generate -D app command, the app The annotations in the folder are automatically converted to native annotations, which is easy and labor-saving~

distributed transaction

In the past year, the Hyperf team also incubated two unprecedented distributed transaction components for the PHP field and contributed to the corresponding open source communities, corresponding to DTM (the first popular distributed transaction manager implemented in Go) and Seata (Popular distributed transaction manager open sourced by Alibaba) Two mainstream open source distributed transaction managers are dtm-php/dtm-client and seata/seata-php, of which dtm-php It is a distributed transaction client that implements the complete functions of dtm, and supports TCC模式,Saga,XA,二阶段消息The distributed transaction mode of the mode, and realized the communication with DTM Server HTTP 协议 or gRPC 协议 communication, the client can safely run in PHP-FPM and Swoole coroutine environment, and it also provides more easy-to-use functional support for the Hyperf framework, which can be applied in the production environment, while seata-php It is still in the development iteration and has not yet been used in the production environment. It is also hoped that more people will participate in the iteration.

We also use a simple example to illustrate how to implement a TCC For the call of distributed transaction and other distributed transaction modes, please refer to the README file of dtm-php repo, or the chapter about distributed transaction in Hyperf 3.0 documentation.

namespace App\\Controller;

use DtmClient\\TCC;
use DtmClient\\TransContext;
use Hyperf\\Di\\Annotation\\Inject;
use Hyperf\\HttpServer\\Annotation\\Controller;
use Hyperf\\HttpServer\\Annotation\\GetMapping;
use Throwable;

#[Controller(prefix: '/tcc')]
class TccController

    protected string $serviceUri = '';

    protected TCC $tcc;

    #[GetMapping(path: 'successCase')]
    public function successCase()
        try {
            $this->tcc->globalTransaction(function (TCC $tcc) {
                // 创建子事务 A 的调用数据
                    // 调用 Try 方法的参数
                    ['amount' => 30],
                    // Try 方法的 URL
                    $this->serviceUri . '/tcc/transA/try',
                    // Confirm 方法的 URL
                    $this->serviceUri . '/tcc/transA/confirm',
                    // Cancel 方法的 URL
                    $this->serviceUri . '/tcc/transA/cancel'
                // 创建子事务 B 的调用数据,以此类推
                    ['amount' => 30],
                    $this->serviceUri . '/tcc/transB/try',
                    $this->serviceUri . '/tcc/transB/confirm',
                    $this->serviceUri . '/tcc/transB/cancel'
        } catch (Throwable $e) {
            var_dump($e->getMessage(), $e->getTraceAsString());
        // 通过 TransContext::getGid() 获得 全局事务ID 并返回
        return TransContext::getGid();


As for other transaction modes, such as Saga,XA,二阶段消息mode, etc., you can refer to the dtm-php/dtm-client The repository’s Readme file or Hyperf 3.0 documentation.

Swow network engine

In fact, in Hyperf 2.2, the operation of the Swow network engine has been supported. With the release of the official version of Swow 1.0, in Hyperf 3.0, we have also raised the application of Swow to a higher level. Swow has implemented a set of ever最完整的 PHP 协程模型it fully releases the true strength of PHP, allowing developers to do things that were unimaginable in the past. Compared with Swoole, it has更好的兼容性,可调试性,可编程性which even enables Hyperf to run on原生 Windows 环境download without resorting to WSL or Docker, and also provides SDB with Watchdog The tool debugs and monitors the running of coroutines, which greatly improves the debuggability of Hyperf.

We provide a brand new Skeleton skeleton project for quickly creating a Hyperf application based on the Swow network engine. The following is a simple pass Composer The process of creating an application:

composer create-project hyperf/swow-skeleton:dev-master 

After creation, make sure your PHP environment has installed the Swow extension, you can directly pass php bin/hyperf.php start Command to start the service, the overall use is the same as before, and the bottom layer of Hyperf has been adapted.In a Windows environment, just add the CMD or Poweshell You can run it in ~

SDB coroutine debugger

SDB Is a written in PHP language协程调试器tool, similar to GDBwhich has the following advantages:

  1. Easy to use, only one line of code is needed to open;
  2. No port required, can run directly on TTY superior;
  3. Zero cost, can be used in production environment without affecting performance;
  4. Powerful functions, deep customization, tailor-made miniature operating system;

pass SDByou can interact with a running Hyperf application to achieve查看当前所有协程状态,窥视协程,进入指定协程,查看调用栈,打断点,单步调试,查看及修改变量调试,扫描僵尸协程,Kill 协程And other operations, in the true sense, bring the PHP coroutine to the engineering实用阶段.


Watchdog Provides CPU scheduling capabilities for PHP, the core principle of which is Watchdog The thread will periodically check the activity of the coroutines in other threads. If it is found that the coroutines in the worker thread are no longer active, pass ZendVM The interrupt mechanism confirms its status, if VM If the interrupt fails, it indicates that the worker thread is blocked by a system call and triggers an alarm; if VM If the interrupt is successful, it means that the worker thread is caught in CPU-intensive operation or infinite loop, and the scheduling rule set by the user will be triggered immediately for scheduling.

pass Watchdog can be realised 可编程的协程调度机制can be very convenient to solve the past headaches CPU 饥饿 Question, here is a demonstration of some usage:

// 运行超过 1ms 就让出控制权
\\Swow\\WatchDog::run(1 * 1000 * 1000);

// 运行超过 1ms 就让出 10ms,调度失败并超过 5ms 时视为系统调用阻塞
\\Swow\\WatchDog::run(1 * 1000 * 1000, 5 * 1000 * 1000, 10);

// 可编程方式,函数会在程序阻塞 100ms 后触发
$alertCountMap = new WeakMap();
\\Swow\\WatchDog::run(quantum: 100 * 1000 * 1000, alerter: static function () use ($alertCountMap): void {
    $coroutine = Coroutine::getCurrent();
    $alertCount = ($alertCountMap[$coroutine] ??= 0) + 1;
    $alertCountMap[$coroutine] = $alertCount;
    echo 'CPU starvation occurred, suspend this coroutine...' . PHP_EOL;
    if ($alertCount > 5) {
        echo 'Kill the bad guy' . PHP_EOL;

More usage

about SDB with WatchDog And more usage The current documentation may not be perfect, we will write many articles to explain the usage in the future, and we will improve the relevant documentation as soon as possible~


Box is a tool dedicated to helping improve the programming experience of PHP applications, especially Hyperf applications, which can be used for管理 PHP 环境和相关依赖while providing the PHP application打包为二进制程序capability, also provides反向代理服务To manage and deploy Swoole/Swow services.These capabilities are also unprecedented, especially the ability to package Hyperf or PHP applications as binary programs. Packaged programs can不依赖系统的 PHP 环境Run alone to achieve packaging capabilities similar to the Go language, these capabilities also benefit from the phpmicro development, while Box is standing on the shoulders of giants, providing these capabilities to everyone in a more simple and easy-to-use way~

The following is a simple example of creating a Hyperf application by downloading Box and running it:

Install Box

// Mac
wget https://github.com/hyperf/box/releases/download/v0.5.5/box_x86_64_macos -O box
sudo mv ./box /usr/local/bin/box
sudo chmod 755 /usr/local/bin/box
// 确保 /usr/local/bin/box 在你的 $PATH 环境中,或者将 `box` 放到你想要的任意 $PATH 路径中

// Linux x86_64
wget https://github.com/hyperf/box/releases/download/v0.5.5/box_x86_64_linux -O box
sudo mv ./box /usr/local/bin/box
sudo chmod 755 /usr/local/bin/box
// 确保 /usr/local/bin/box 在你的 $PATH 环境中,或者将 `box` 放到你想要的任意 $PATH 路径中

// Windows
curl -o box.exe https://github.com/hyperf/box/releases/download/v0.5.5/box_x64_windows.exe
// 将 `box.exe` 放到你想要的任意 Path 环境变量路径中,同时 Windows 版本在执行时需要在命令行中使用 `box.exe` 而不是 `box`

Initialize Github Access Token

Box requires a Github access token to make requests to the Github API in order to retrieve package versions from Artifacts in GitHub Actions.

  1. Create a Github Access Token,workflow The scope needs to be checked;
  2. run box config set github.access-token <Your Token> command to set your token;

We will make it unnecessary to set up Github Access Token before using Box in version v0.6 to provide a more convenient user experience, please look forward to it~

Initialize the PHP environment and start Hyperf through Box

// 通过 box 安装 PHP 8.1,此安装不会影响系统原来自身安装的 PHP
box get php@8.1
// 通过 box 安装 composer
box get composer
// 通过 box composer 创建 hyperf 应用,可指定 dev-master 分支以防止 packagist 代理数据落后的问题
box composer create-project hyperf/swow-skeleton:dev-master
// 通过 box 启动 hyperf
box hyperf start

So far, a complete installation and operation process has been completed. We can find that the complex environment deployment process in the past has been simplified to a few commands. Through && Connectors can even make up a single line of commands.

Package Hyperf application as a binary program through Box

this神奇的能力the operation is also simplified beyond belief, only need to pre-execute box build-prepare The command downloads the relevant dependencies in advance. This command only needs to be executed once, and it can be passed later. box build The command packs the Hyperf application in the current folder.After packaging, a file named hyperf The binary file, the follow-up only needs to pass hyperf start command to start the Hyperf application.

Box itself is a Hyperf application packaged based on Box. You can also understand the use of this capability by understanding the Box project itself.

Box Kernel toggle

By default, Box consists of Swow Kernel provides support, but we also provide Swoole Kernel, you can pass box config set kernel swoole to switch to Swoole Kernel, but it should be noted that Swoole Kernel only supports PHP 8.1 version, and不支持Build binary program functions and Windows system environment.

// 设置为 Swow Kernel [默认]
box config set kernel swow

// 设置为 Swoole Kernel (不支持 Windows)
box config set kernel swoole

More Capabilities of Box

Box has more interesting usage methods and tool combinations, which can be quickly glanced through the command list in the following part


box get pkg@version从远程安装包,pkg是包名,version是包的版本,box get pkg表示安装最新版本的 pkg,例如, 运行 box get php@8.1 安装 PHP 8.1, 运行 box get composer 安装最新的 composer bin
box build-prepare 为 build 和 build-self 命令做好相关环境的准备
box build-self 构建 box bin 本身
box build <path> 将 Hyperf 应用程序构建成二进制文件
box self-update 将 box bin 更新至最新版本
box config set-php-version <version>设置 box 的当前 PHP 版本,可用值:8.0 | 8.1
box config get-php-version <version>获取 box 的当前设置的 PHP 版本
box reverse-proxy -u <upsteamHost:upstreamPort> 启动一个反向代理 HTTP 服务器,用于将 HTTP 请求转发到指定的多个上游服务器
box php <argument> 通过当前 box 的 PHP 版本运行任何 PHP 命令
box composer <argument>通过当前 box 的 PHP 版本运行任何 Composer 命令
box php-cs-fixer <argument> 通过当前 box 的 PHP 版本运行任何 php-cs-fixer 命令
box cs-fix <argument> 通过当前 box 的 PHP 版本运行 php-cs-fixer fix 命令
box phpstan <argument> 通过当前 box 的 PHP 版本运行任何 phpstan 命令
box pint <argument> 通过当前 box 的 PHP 版本运行任何 pint 命令

more optimization

Hyperf 3.0 has still done a lot of optimization and adjustment, you can read the CHANGELOG-3.0.md file in the Hyperf main warehouse for details.

At the same time, we have also prepared a guide for upgrading from 2.2 to 3.0. For details, please refer to the chapter of Hyperf Official Documentation – 3.0 Upgrade Guide.

#Hyperf #era #PHP #News Fast Delivery

Leave a Comment

Your email address will not be published. Required fields are marked *