Skip to content

Instantly share code, notes, and snippets.

@jason-napolitano
Last active November 26, 2025 05:06
Show Gist options
  • Select an option

  • Save jason-napolitano/c61620734804857527a2607389c88c43 to your computer and use it in GitHub Desktop.

Select an option

Save jason-napolitano/c61620734804857527a2607389c88c43 to your computer and use it in GitHub Desktop.
A loader file use to load array data returned by PHP files within a directory (EG: configuration data)
<?php
class Loader
{
/** @var array $cache */
protected static array $cache = [];
/** @var string $path */
protected static string $path = __DIR__ . '/../path/to/directory/where/files/are/located';
/**
* Get a config value using dot notation:
*
* EG: "database.hostname"
*/
public static function get(string $key, mixed $default = null): mixed
{
[$file, $path] = self::splitKey($key);
$config = self::loadFile($file);
// Walk through nested keys (like hostname inside database)
foreach ($path as $segment) {
if (!is_array($config) || !array_key_exists($segment, $config)) {
return $default;
}
$config = $config[$segment];
}
return $config;
}
/**
* Load an entire config file, with caching.
*/
public static function load(string $file): array
{
return self::loadFile($file);
}
/**
* Internal: load the config file and cache it.
*/
protected static function loadFile(string $file): array
{
if (!isset(self::$cache[$file])) {
$path = self::$path . '/' . $file . '.php';
if (!file_exists($path)) {
throw new Config\ConfigFileNotFound("Config file '$file' not found at '$path'");
}
self::$cache[$file] = include $path;
}
return self::$cache[$file];
}
/**
* Split "database.hostname" into ["database", ["hostname"]]
*/
protected static function splitKey(string $key): array
{
$parts = explode('.', $key);
$file = array_shift($parts);
return [$file, $parts];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment