EasySwoole 使用*.ini格式的配置文件

EasySwoole 使用*.ini格式的配置文件

簡介

本文章帶領(lǐng)大家學(xué)習(xí)如何在EasySwoole使用ini格式的配置文件。

ini的優(yōu)缺點(diǎn)

優(yōu)點(diǎn):線性的、簡單、簡練、方便

缺點(diǎn):復(fù)雜類型的數(shù)據(jù)配置無力

目錄結(jié)構(gòu)

.
├── App
│   ├── HttpController
│   │   └── Productor.php
│   ├── Process
│   │   └── Consumer.php
│   └── Resource
│       └── RedisPool.php
├── Config
│   └── Ini
│       ├── database.ini
│       └── redis.ini
├── EasySwooleEvent.php
├── Ini
│   └── src
│       └── Ini.php
xxx

Ini包源碼

非常簡單

<?php
/**
 * @CreateTime:   2020/5/3 下午6:30
 * @Author:       huizhang  <tuzisir@163.com>
 * @Copyright:    copyright(2020) Easyswoole all rights reserved
 * @Description:  解析ini配置文件
 */
namespace EasySwoole\Ini;

use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Config;
use EasySwoole\Spl\SplArray;

class Ini
{
    use Singleton;

    protected $iniDir;

    public function __construct()
    {
        $this->iniDir = Config::getInstance()->getConf('INI_DIR');
    }

    public function setDir($iniDir)
    {
        $this->iniDir = $iniDir;
        return $this;
    }

    public function getConf(string $fileName, $key)
    {
        return $this->parseConf($fileName, $key);
    }

    private function parseConf($fileName, $key)
    {
        $config = parse_ini_file($this->iniDir.'/'.$fileName.'.ini', true);

        if ($key == null) {
            return $config;
        }

        if (empty($key)) {
            return null;
        }
        if (strpos($key, '.') > 0) {
            $temp = explode('.', $key);
            if (is_array($config)) {
                $data = new SplArray($config);
                return $data->get(implode('.', $temp));
            }
        }

        return $config[$key];
    }
}

配置文件格式

database.ini

; 訂單數(shù)據(jù)庫
[order]
host=127.0.0.1
port=3306
user=admin
password=123456
database=order

; 用戶數(shù)據(jù)庫
[user]
host=127.0.0.1
port=3306
user=admin
password=123456
database=user

配置Ini配置文件的默認(rèn)目錄

配置ini文件的目錄有兩種方式

1. 在EasySwoole的配置文件中,比如dev.php
<?php
return [
    'SERVER_NAME' => "EasySwoole",
    'MAIN_SERVER' => [
        xxx
    ],
    'INI_DIR' => EASYSWOOLE_ROOT.'/Config/Ini' // 指定ini配置文件的目錄
];
2. 在mainServerCreate方法中注冊
public static function mainServerCreate(EventRegister $register)
{
    Ini::getInstance()->setDir(EASYSWOOLE_ROOT.'/Config/Ini');
}

使用方式

// 獲取database.ini中的所有配置
Ini::getInstance()->getConf('database');

// 獲取database.ini中的一塊配置
Ini::getInstance()->getConf('database', 'order');

// 獲取database.ini中的一塊配置的某一項(xiàng)
Ini::getInstance()->getConf('database', 'order.host');

EasySwoole

官網(wǎng):http://www.easyswoole.com

交流群:932625047

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容