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

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

簡介

本文章帶領你們學習如何在EasySwoole使用ini格式的配置文件。php

ini的優缺點

優勢:線性的、簡單、簡練、方便redis

缺點:複雜類型的數據配置無力數據庫

目錄結構

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

Ini包源碼

很是簡單swoole

<?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學習

; 訂單數據庫
[order]
host=127.0.0.1
port=3306
user=admin
password=123456
database=order

; 用戶數據庫
[user]
host=127.0.0.1
port=3306
user=admin
password=123456
database=user

配置Ini配置文件的默認目錄

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

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中的一塊配置的某一項
Ini::getInstance()->getConf('database', 'order.host');

EasySwoole

官網:http://www.easyswoole.comthis

交流羣:932625047url

相關文章
相關標籤/搜索