hyperf 框架动态修改或追加配置

需求背景

最近开发一个组件,有一个功能需要由组件提供配置,然后根据组件配置连接数据库

解决思路

查看文档发现框架的配置都是存储在 Hyperf\Contract\ConfigInterface 对象中,只要能把配置写入这个对象中,那么在项目中就可以通过 config() 函数获取到,实现动态连接数据库。

熟悉 hyperf 框架的都知道,hyper 框架是基于 swoole 实现,常驻内存框架,框架一运行起来配置都在内存中无法修改和写入,然后查看框架生命周期,发现框架有提供不同事件,可以在框架启动时动态写入配置,基于这两个特性,通过自定义监听器实现追加配置到框架中。

文档:
hyperf.wiki/2.1/#/zh-cn/event
https://hyperf.wiki/2.2/#/zh-cn/config?id=configphp-%e4%b8%8e-autoload-%e6%96%87%e4%bb%b6%e5%a4%b9%e5%86%85%e7%9a%84%e9%85%8d%e7%bd%ae%e6%96%87%e4%bb%b6%e7%9a%84%e5%85%b3%e7%b3%bb

实现过程

自定义监听器

<?php

declare(strict_types=1);

namespace App\Listener;

use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Framework\Event\AfterWorkerStart;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * @Listener
 */
class DataModelListener implements ListenerInterface
{
    /**
     * @Inject
     * @var \Hyperf\Contract\ConfigInterface
     */
    public $configInterface;

    public function listen(): array
    {
       // 事件
        return [
            AfterWorkerStart::class,
        ];
    }

    public function process(object $event)
    {
        // 读取组件配置
        $config = config('xx.xx');
        // 写入配置
        $this->configInterface::set('databases.test', $config);
    }
}

这样通过监听器在框架启动时写入配置,就可以项目中读取。

本作品采用《CC 协议》,转载必须注明作者和本文链接
微信订阅号:Nick同学
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!