Skip to content

Instantly share code, notes, and snippets.

@Alexisgt01
Last active July 14, 2020 19:48
Show Gist options
  • Save Alexisgt01/c0f4549e24f433a82116d9d6d9eebdf7 to your computer and use it in GitHub Desktop.
Save Alexisgt01/c0f4549e24f433a82116d9d6d9eebdf7 to your computer and use it in GitHub Desktop.
Get data from a directory and merge it into an array
// config/app.php
<?php
return [
'app' => 'app_name',
'url' => 'localhost:8080',
];
<?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