brief introduction
This article takes you through how to use ini configuration files in easysoole.
Advantages and disadvantages of ini
Advantages: linear, simple, concise and convenient
Disadvantages: weak data configuration of complex types
directory structure
. ├── App │ ├── HttpController │ │ └── Productor.php │ ├── Process │ │ └── Consumer.php │ └── Resource │ └── RedisPool.php ├── Config │ └── Ini │ ├── database.ini │ └── redis.ini ├── EasySwooleEvent.php ├── Ini │ └── src │ └── Ini.php xxx
Ini package source code
It's simple
<?php /** * @CreateTime: 2020/5/3 6:30 pm * @Author: huizhang <tuzisir@163.com> * @Copyright: copyright(2020) Easyswoole all rights reserved * @Description: Parsing ini configuration file */ 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]; } }
Profile format
database.ini
; Order database [order] host=127.0.0.1 port=3306 user=admin password=123456 database=order ; User database [user] host=127.0.0.1 port=3306 user=admin password=123456 database=user
Configure default directory for Ini profiles
There are two ways to configure the directory of the ini file
1. In the configuration file of easysoole, for example, dev.php
<?php return [ 'SERVER_NAME' => "EasySwoole", 'MAIN_SERVER' => [ xxx ], 'INI_DIR' => EASYSWOOLE_ROOT.'/Config/Ini' // Specify the directory for the ini configuration file ];
2. Register in the mainServerCreate method
public static function mainServerCreate(EventRegister $register) { Ini::getInstance()->setDir(EASYSWOOLE_ROOT.'/Config/Ini'); }
How to use
// Get all configurations in database.ini Ini::getInstance()->getConf('database'); // Get a piece of configuration in database.ini Ini::getInstance()->getConf('database', 'order'); // Get a piece of configuration in database.ini Ini::getInstance()->getConf('database', 'order.host');
EasySwoole
Official website: http://www.easyswoole.com
Communication group: 932625047