hyperf| hyperf 源码解读 1: 启动

简介: hyperf| hyperf 源码解读 1: 启动

hyperf 的准备工作做好后, 就开始运行启动命令了:

php bin/hyperf

可以看到如下输出:

root@820d21e61cd8 /d/hyperf-demo# php bin/hyperf.php
Scanning ...
Scan completed.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Di\Listener\BootApplicationListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\RpcClient\Listener\AddConsumerDefinitionListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Paginator\Listener\PageResolverListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\JsonRpc\Listener\RegisterProtocolListener listener.
Console Tool

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  help               Displays help for a command
  info               Dump the server info.
  list               Lists commands
  migrate
  start              Start swoole server.
  t                  Hyperf Demo Command
 db
  db:model
 di
  di:init-proxy
 gen
  gen:amqp-consumer  Create a new amqp consumer class
  gen:amqp-producer  Create a new amqp producer class
  gen:aspect         Create a new aspect class
  gen:command        Create a new command class
  gen:controller     Create a new controller class
  gen:job            Create a new job class
  gen:listener       Create a new listener class
  gen:middleware     Create a new middleware class
  gen:migration
  gen:process        Create a new process class
 migrate
  migrate:fresh
  migrate:install
  migrate:refresh
  migrate:reset
  migrate:rollback
  migrate:status
 queue
  queue:flush        Delete all message from failed queue.
  queue:info         Delete all message from failed queue.
  queue:reload       Reload all failed message into waiting queue.
 vendor
  vendor:publish     Publish any publishable configs from vendor packages.

今天要看这么多内容么? 不, 只看这部分:

root@820d21e61cd8 /d/hyperf-demo# php bin/hyperf.php
Scanning ...
Scan completed.

...

这部分就是整个框架的核心, 这部分搞清楚了, 后面都是搭积木了, 随用随取.

PS: 看源码, 尤其是优秀开源项目的源码, 是程序员进阶的「终南捷径」.

入口: bin/hyperf.php

#!/usr/bin/env php
<?php

use Hyperf\Contract\ApplicationInterface;

// php ini 设置
ini_set('display_errors', 'on');
ini_set('display_startup_errors', 'on');

error_reporting(E_ALL);

// 定义常量 BASE_PATH, 所有路径相关都会使用这个常量
!defined('BASE_PATH') && define('BASE_PATH', dirname(__DIR__, 1));

// composer 自动加载
require BASE_PATH . '/vendor/autoload.php';

// Self-called anonymous function that creates its own scope and keep the global namespace clean.
(function () {
    // container
    /** @var \Psr\Container\ContainerInterface $container */
    $container = require BASE_PATH . '/config/container.php';

    // application
    $application = $container->get(ApplicationInterface::class);
    $application->run();
})();

很简单的几部分:

  • PHP ini 设置, 按需设置即可, 比如这里还可以设置时区
  • 常量 BASE_PATH, hyperf 只设置了这个一个常量, 用来所有 路径 相关的场景
  • config/container.php, container 的初始化, 重中之重的内容
  • Application->run(), 完整的是 Symfony\Component\Console\Application, 用来跑 cli 应用
PS: 有轮子, 而且还很好用, 干嘛非要自己造. 这也是要读源码的理由之一.

重点: config/container.php

到重点内容了, 重要的事情说三遍

use Hyperf\Config\ProviderConfig;
use Hyperf\Di\Annotation\Scanner;
use Hyperf\Di\Container;
use Hyperf\Di\Definition\DefinitionSource;
use Hyperf\Utils\ApplicationContext;

// 使用 composer 提供的工具 ProviderConfig 
$configFromProviders = ProviderConfig::load();

// dependency
$definitions = include __DIR__ . '/dependencies.php';
$serverDependencies = array_replace($configFromProviders['dependencies'] ?? [], $definitions['dependencies'] ?? []);

// annotation
$annotations = include __DIR__ . '/autoload/annotations.php';
$scanDirs = $configFromProviders['scan']['paths'];
$scanDirs = array_merge($scanDirs, $annotations['scan']['paths'] ?? []);

// scan
$ignoreAnnotations = $annotations['scan']['ignore_annotations'] ?? ['mixin'];

// container 初始化
$container = new Container(new DefinitionSource($serverDependencies, $scanDirs, new Scanner($ignoreAnnotations)));

if (! $container instanceof \Psr\Container\ContainerInterface) {
    throw new RuntimeException('The dependency injection container is invalid.');
}

// 设置后, 方便全局获取 container 实例
return ApplicationContext::setContainer($container);

使用 composer 提供的工具 ProviderConfig

// \Hyperf\Config\providers
$providers = Composer::getMergedExtra('hyperf')['config'] ?? [];

关键是这句, 对应获取到的 composer.json 文件中的配置:

    "extra": {
        "branch-alias": {
            "dev-master": "1.1-dev"
        },
        // 对应这里的配置
        "hyperf": {
            "config": "Hyperf\\Amqp\\ConfigProvider"
        }
    },

对应的 ConfigProvider 内容:

namespace Hyperf\Amqp;

use Hyperf\Amqp\Packer\Packer;
use Hyperf\Utils\Packer\JsonPacker;

class ConfigProvider
{
    public function __invoke(): array
    {
        return [
            'dependencies' => [
                Producer::class => Producer::class,
                Packer::class => JsonPacker::class,
                Consumer::class => ConsumerFactory::class,
            ],
            'commands' => [
            ],
            'scan' => [
                'paths' => [
                    __DIR__,
                ],
            ],
            'publish' => [
                [
                    'id' => 'config',
                    'description' => 'The config for amqp.',
                    'source' => __DIR__ . '/../publish/amqp.php',
                    'destination' => BASE_PATH . '/config/autoload/amqp.php',
                ],
            ],
        ];
    }
}

这里有 4 部分内容:

  • dependencies: 依赖关系, 解耦神器
  • commands: 部分 hyperf 组件有有自定义的 command, php bin/hyperf.php 看到的命令, 配置就是这里来的
  • scan: 设置扫描目录, hyperf 组件是默认是组件源码目录 src/
  • publish: 通常用来加载组件提供的默认配置文件, 或者其他一些组件提供的 demo 文件

container 初始化

// \Hyperf\Di\Definition\DefinitionSource::__construct
$container = new Container(new DefinitionSource($serverDependencies, $scanDirs, new Scanner($ignoreAnnotations)));

别看只有一行, 这里干的事情可真不少, 要得到 container 这个 缺啥都找它要 的神器, 当然没那么简单(哼起来~)

关键代码是这里:

// \Hyperf\Di\Definition\DefinitionSource::scan
    private function scan(array $paths): bool
    {
        if (empty($paths)) {
            return true;
        }
        $pathsHash = md5(implode(',', $paths));
        if ($this->hasAvailableCache($paths, $pathsHash, $this->cachePath)) {
            $this->printLn('Detected an available cache, skip the scan process.');
            [, $annotationMetadata, $aspectMetadata] = explode(PHP_EOL, file_get_contents($this->cachePath));
            // Deserialize metadata when the cache is valid.
            AnnotationCollector::deserialize($annotationMetadata);
            AspectCollector::deserialize($aspectMetadata);
            return false;
        }
        $this->printLn('Scanning ...');
        // 关键在这里
        $this->scanner->scan($paths);
        $this->printLn('Scan completed.');
        if (! $this->enableCache) {
            return true;
        }
        // enableCache: set cache
        if (! file_exists($this->cachePath)) {
            $exploded = explode('/', $this->cachePath);
            unset($exploded[count($exploded) - 1]);
            $dirPath = implode('/', $exploded);
            if (! is_dir($dirPath)) {
                mkdir($dirPath, 0755, true);
            }
        }
        $data = implode(PHP_EOL, [$pathsHash, AnnotationCollector::serialize(), AspectCollector::serialize()]);
        file_put_contents($this->cachePath, $data);
        return true;
    }

看起来有点复杂呀, 别慌, 一言以蔽之, scan 是为了给我们想要的数据:

AnnotationCollector::serialize()
AspectCollector::serialize()

没错, 注解(Annotation) + Aspect(切面)

container 使用

基于 hyperf 的应用中, 缺啥都找 container 就对了, 具体的文档可以参考 hyperf doc - 依赖注入

这里补充 2 点, 一个是 container 的补充说明:

// \Hyperf\Di\Container::get
    public function get($name)
    {
        // If the entry is already resolved we return it
        if (isset($this->resolvedEntries[$name]) || array_key_exists($name, $this->resolvedEntries)) {
            return $this->resolvedEntries[$name];
        }
        $this->resolvedEntries[$name] = $value = $this->make($name);
        return $value;
    }

上看 scan 看似复杂, 最终都会处理到 container 的 $this->resolvedEntries[$name] 变量里, 不明白的话, 可以把这变量打印一下看一看

第二点对转到 依赖注入 下的小伙伴说的:

自己 new 出来的变量是无法用到强大的 container 的, 以及之后各类好用的方法, 真爱生命, 不要瞎 new 哦~

写到最后

hyperf 最核心的部分我们已经看到了, 没错, 就是 container, container 在手, 天下我有.

下篇预告: 依旧从安装 hyperf 就会执行的命令 php bin/hyperf.php start 入手, 强大的 swoole 在呼唤着我们 !
目录
相关文章
|
3月前
|
人工智能 IDE 开发工具
Pi 突然火了:极简 Coding Agent 到底强在哪里?
本文导读 大多数 Coding Agent 都在继续增加模型、工具和连接器,Pi 却把默认能力压到很小,再由用户按需扩展。本文不按 Star 数下结论,而是分析这种极简设计换来了什么、付出了什么,以及它适合哪类使用者。 AI 编程工具正在走一条很熟悉的路。 模型要更多,工具要更多,MCP 要更多,A
Pi 突然火了:极简 Coding Agent 到底强在哪里?
|
数据采集 存储 运维
DAMA数据管理知识体系指南(3):数据治理
DAMA:国际数据管理协会,是一个全球性数据管理和业务专业志愿人士组成的非营利协会,是当前国际上在数据治理领域最权威的机构。 DMBOK2则是DAMA组织众多数据管理领域的国际级资深专家编著,深入阐述数据管理各领域的完整知识体系。它是市场上唯一综合了数据管理方方面面的一部权威性著作。 本系列文章,将针对DMBOK中的核心内容进行解读。
DAMA数据管理知识体系指南(3):数据治理
|
6月前
|
设计模式 人工智能 开发框架
微软竟然出了免费的 AI 应用开发课?!我已经学上了
大家好,我是程序员鱼皮。最近又挖到一个好东西,微软在 GitHub 上开源了一套 AI Agent 零基础课程,叫《AI Agents for Beginners》,目前 Star 已经突破 5 万了。 课程指路:https://github.com/microsoft/aiagentsforbeginners 整套课程一共 15 节(还在持续更新中),每节都配了文章、视频和代码示例,而且 还有中
1956 0
|
11月前
|
人工智能 弹性计算 运维
阿里云2026年优惠建站费用全解析:三种方案的价格、功能与选型指南
在数字化需求不断增长的当下,搭建网站成为个人展示、企业推广的重要方式。阿里云针对不同技术基础和业务规模,推出了 “自购服务器建站”“万小智 AI 模板建站”“云企业官网定制建站” 三种核心方案,价格从每年几十元到数万元不等,能满足从个人到中大型企业的各类需求。下面结合最新信息,从方案细节、价格、功能和适配场景等方面展开解析,为大家提供客观的选型参考。
|
6月前
|
人工智能 前端开发 Shell
用完Zed之后,我发现了VS Code 和Zed的一个重大区别
作者尝试Zed等轻量编辑器后,发现VS Code真正的优势在于“工作流连续性”:自动恢复终端历史、工作目录、分屏布局与命令上下文,极大降低心智负担。这并非功能堆砌,而是将终端深度融入开发环境的状态管理——轻快易用与环境记忆之间,开发者终需权衡。(239字)
538 0
|
9月前
|
JSON Go PHP
告别阻塞!用 PHP TrueAsync 实现 PHP 脚本提速 10 倍
本文介绍如何用 PHP TrueAsync 构建高性能进程池:基于 `proc_open` 与 NDJSON 协议实现非阻塞进程通信,结合 Channel 任务分发、TaskGroup 协程管理及 Supervisor 自愈机制,让同步 PHP 函数在协程中高效并行,轻松提速 10 倍。
354 19
|
监控 供应链 API
速卖通商品 API,开发者示例
速卖通商品API是速卖通开放平台为开发者提供的接口,支持获取商品详情、订单管理等功能。具备多语言、多货币支持,适用于全球电商场景。可应用于商品分析、价格监控、竞品对比和库存管理等业务。文档提供Python调用示例,便于快速集成使用。
|
12月前
|
存储 监控 安全
金融级云架构安全合规设计
金融级云架构安全合规设计是数字金融发展的基石。本文从等保三级、PCI DSS合规要求出发,系统阐述网络隔离、数据加密、访问控制、高可用架构、审计监控与数据全生命周期管理等核心设计,结合互联网银行实践案例与合规检查清单,构建纵深防御体系,助力金融机构实现安全、稳定、合规的云上转型。(238字)
851 0
|
搜索推荐 小程序 物联网
基于HarmonyOS 5.0的元服务:技术架构、应用场景与未来发展【探讨】
鸿蒙OS 5.0推出的元服务(Super Service)是一种创新的服务架构,旨在提供无缝的跨设备体验。它具备无感知启动、跨设备共享和智能推送等特点,适用于智能家居、车载系统、即时通讯等场景。与传统应用及微信小程序相比,元服务更轻量、跨平台能力强,且无需下载安装。未来,元服务将通过AI增强智能化,并扩展到更多行业,如智慧医疗、智能零售等,推动物联网和智慧城市的发展。然而,其发展仍面临平台依赖、隐私安全等挑战。
基于HarmonyOS 5.0的元服务:技术架构、应用场景与未来发展【探讨】
|
安全 开发工具 git
git合并错了,我想回退到之前的版本
git合并错了,我想回退到之前的版本