Last active
November 26, 2025 05:06
-
-
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)
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 | |
| 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