Skip to content

Commit

Permalink
init: PHP Config Class
Browse files Browse the repository at this point in the history
  • Loading branch information
zjd committed Dec 5, 2019
1 parent d93c5f5 commit 11f74c6
Show file tree
Hide file tree
Showing 8 changed files with 1,726 additions and 0 deletions.
85 changes: 85 additions & 0 deletions Config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php
/**
* Created by PhpStorm.
* User: Jordy
* Date: 2019/12/5
* Time: 6:03 PM
*/

namespace All\Config;

use Ali\InstanceTrait;
use All\Exception\WarnException;

class Config
{
use InstanceTrait;

private $path;
private $data;

public function setPath($path)
{
$this->path = $path;
return $this;
}

/**
* @return mixed
* @throws WarnException
*/
public function getPath()
{
if (!$this->path) {
throw new WarnException('Config path is not configured');
}
return $this->path;
}

/**
* @param string $key example: db/default.master.host
* @return array|null
* @throws \Exception
*/
public function get($key)
{
list($file, $keys) = $this->parseKey($key);
$data = $this->getData($file);
if (!$keys || !$data) {
return $data;
}
foreach ($keys as $key) {
if (!is_array($data) || !isset($data[$key])) {
return null;
}
$data = $data[$key];
}
return $data;
}

/**
* @param $file
* @return array|null
* @throws WarnException
*/
private function getData($file)
{
if (isset($this->data[$file])) {
return $this->data[$file];
}
$filePath = $this->getPath() . DIRECTORY_SEPARATOR . $file . '.php';
if (!is_file($filePath) || !is_readable($filePath)) {
return null;
}
$data = include $filePath;
$data = $data && is_array($data) ? $data : [];
return $this->data[$file] = $data;
}

private function parseKey($key)
{
$keys = explode('.', $key);
$file = trim(array_shift($keys), '/');
return [$file, $keys];
}
}
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,12 @@
# php-config
PHP 配置类

## Usage

```php
<?php
$config = Config::getInstance();
$config->setPath('./');

$data = $config->get('path1/filename.level1.level2');
```
26 changes: 26 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "boxunphp/php-config",
"description": "PHP 配置类",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Jordy",
"email": "arno.zheng@gmail.com"
}
],
"minimum-stability": "dev",
"require-dev": {
"phpunit/phpunit": "7.*"
},
"require": {
"php": "^7.1",
"boxunsoft/php-instance": "^v1.1.0",
"boxunphp/php-exception": "^v1.0.0"
},
"autoload": {
"psr-4": {
"All\\Config\\": ""
}
}
}

0 comments on commit 11f74c6

Please sign in to comment.