Last active
July 14, 2020 19:48
-
-
Save Alexisgt01/c0f4549e24f433a82116d9d6d9eebdf7 to your computer and use it in GitHub Desktop.
Get data from a directory and merge it into an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// config/app.php | |
<?php | |
return [ | |
'app' => 'app_name', | |
'url' => 'localhost:8080', | |
]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Core\Service; | |
class Config | |
{ | |
/** | |
* @var string $directory | |
* Directory | |
*/ | |
private static $directory = 'config'; | |
/** | |
* @var $settings | |
* All config in array | |
*/ | |
private static $settings; | |
/** | |
* @param string $key | |
* @return string | |
* Get value from config directory | |
*/ | |
public static function get($key) | |
{ | |
if (is_null(self::$settings)) { | |
self::$settings = self::merge_config(); | |
} | |
return self::$settings[$key]; | |
} | |
/** | |
* @return array $result | |
* merge all php files | |
*/ | |
protected static function merge_config() | |
{ | |
$configs = glob(ROOT . DIRECTORY_SEPARATOR . self::$directory . DIRECTORY_SEPARATOR . '*.php'); | |
$result = []; | |
foreach ($configs as $conf) { | |
$file = str_replace('.php', '' , explode(DIRECTORY_SEPARATOR, $conf)[sizeof(explode(DIRECTORY_SEPARATOR, $conf)) - 1]); | |
$c = include $conf; | |
array_walk($c, function ($v, $k) use (&$result, $file) { | |
$result[$file . '.' . $k] = $v; | |
}); | |
} | |
return $result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment