easyswoole实现载入自定义配置文件夹所有配置文件的封装

修改easyswoole的配置类

//类文件路径 //easyswoole/vendor/easyswoole/easyswoole/src/Config.php

//引入File组件
use EasySwoole\Utility\File;

//在类中定义方法
/**
     * 载入自定义配置文件夹里的所有配置文件
     * @param string $dirPath 配置文件夹
     * @param bool $merge 是否将内容合并入主配置
     * @author : lqx_chris
     */
    public function loadDir (string $dirPath, bool $merge = false)
    {
        if(is_dir($dirPath)){
            $fileList = File::scanDirectory($dirPath);
            foreach ($fileList['files'] as $filePath){
                $this->loadFile($filePath,$merge);
            }
        }
    }

创建自己的配置目录

例:在 cache.php 和 database.php 配置文件中,我们简单写一些东西

//cache.php
return [
  'REDIS'=>'redis',
];
//database.php
return [
  'MYSQL' => [
        'host'          => '127.0.0.1',
        'port'          => '3306',
        'user'          => 'root',
        'timeout'       => '5',
        'charset'       => 'utf8mb4',
        'password'      => '123456',
        'database'      => 'easyswoole',
    ],
];

在 EasySwooleEvent.php 的 initialize 事件中载入配置

<?php
namespace EasySwoole\EasySwoole;


use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\ORM\Db\Config as ORMConfig;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Db\Connection;

class EasySwooleEvent implements Event
{

    public static function initialize()
    {
        // TODO: Implement initialize() method.
        date_default_timezone_set('Asia/Shanghai');
        //载入配置文件夹文件
        Config::getInstance()->loadDir(EASYSWOOLE_ROOT . '/Config', true);
        //配置ORM
        $config = new ORMConfig(Config::getInstance()->getConf("MYSQL"));
        //注册ORM连接池
        DbManager::getInstance()->addConnection(new Connection($config));
    }

    public static function onRequest(Request $request, Response $response): bool
    {
        // TODO: Implement onRequest() method.
        // 请求进来时输出一下配置信息,看看是否成功
        var_dump(Config::getInstance()->getConf());
        return true;
    }
}
//启动
$ php easyswoole start
//请求Easyswoole
localhost:9501
//输出信息中,除了主配置,我们可以看到我们自己文件夹的配置也合并载入了
  ["MYSQL"]=>
  array(7) {
    ["host"]=>
    string(9) "127.0.0.1"
    ["port"]=>
    string(4) "3306"
    ["user"]=>
    string(4) "root"
    ["timeout"]=>
    string(1) "5"
    ["charset"]=>
    string(7) "utf8mb4"
    ["password"]=>
    string(5) "12345"
    ["database"]=>
    string(6) "easyswoole"
  }
  ["REDIS"]=>
  string(5) "redis"

已经更新此封装到 EasySwoole 3.4x的版本中,使用3.4x版本的同学可以直接使用啦~~~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值