VOOZH about

URL: https://deepwiki.com/hypervel/config/6.3-file-based-configuration

⇱ File-Based Configuration | hypervel/config | DeepWiki


Loading...
Menu

File-Based Configuration

Purpose and Scope

This document explains how the ConfigFactory discovers and loads configuration files from the file system during application bootstrap. It covers the two primary file-based configuration sources: the root config/hyperf.php file and PHP files within the config/autoload/ directory. The document also details the key generation mechanism that transforms file paths into configuration keys using dot notation.

For information about how provider-based configurations are discovered from Composer packages, see Provider Config Discovery and Merging. For details on how ConfigFactory orchestrates the entire configuration loading process, see Configuration Factory.

Configuration File Locations

The ConfigFactory loads configuration files from two primary locations within the application's base path:

LocationPathLoading MethodPurpose
Root Configurationconfig/hyperf.phpDirect loadBase application configuration
Autoload Directoryconfig/autoload/*.phpDirectory scanModular configuration files

The factory automatically detects the presence of the autoload directory and includes it in the scan paths if it exists, maintaining compatibility with Hyperf's standard folder structure src/ConfigFactory.php15-20

Sources: src/ConfigFactory.php15-20

File System Structure


Diagram: File System Structure and Discovery Paths

This diagram shows how ConfigFactory discovers files from the file system. The readConfig() method loads the single root file, while readPaths() scans the autoload directory recursively.

Sources: src/ConfigFactory.php15-23 src/ConfigFactory.php46-65

Root Configuration File

The root configuration file at config/hyperf.php is loaded directly by the readConfig() method. This method:

  1. Checks if the file exists and is readable
  2. Requires the PHP file to obtain the returned array
  3. Validates that the result is an array, defaulting to an empty array if not

Diagram: Root Configuration File Loading Sequence

The readConfig() method implementation ensures safe loading with validation src/ConfigFactory.php36-44:

  • Line 39: Checks file existence and readability
  • Line 40: Uses require to load the file
  • Line 43: Validates the result is an array

Sources: src/ConfigFactory.php36-44

Autoload Directory Configuration

The autoload directory provides a modular approach to configuration, allowing multiple configuration files to be organized by concern. The readPaths() method handles the discovery and loading of these files.

Discovery Process

The method uses Symfony Finder to locate all PHP files within the specified paths:

  1. Creates a Finder instance
  2. Configures it to find files with .php extension
  3. Excludes specified files (notably hyperf.php to prevent duplication)
  4. Iterates through discovered files

src/ConfigFactory.php46-65 shows the complete implementation.

Configuration Key Generation

Each file in the autoload directory is transformed into a nested configuration structure using a key generation algorithm:


Diagram: Configuration Key Generation from File Paths

The key generation mechanism src/ConfigFactory.php56-59 follows this algorithm:

  1. Get Relative Path: $file->getRelativePath() returns the path relative to the scan directory
  2. Transform Path: str_replace('/', '.', ...) converts directory separators to dots
  3. Get Base Name: $file->getBasename('.php') returns filename without extension
  4. Filter Empty: array_filter([...]) removes empty strings (for root-level files)
  5. Join Components: implode('.', ...) creates the final dot-notation key

Sources: src/ConfigFactory.php56-59

Key Generation Examples

The following table illustrates how different file paths are transformed into configuration keys:

File PathRelative PathBase NameGenerated KeyResult Structure
autoload/app.php""appapp['app' => [...]]
autoload/database.php""databasedatabase['database' => [...]]
autoload/cache/redis.phpcacherediscache.redis['cache' => ['redis' => [...]]]
autoload/services/api/client.phpservices/apiclientservices.api.client['services' => ['api' => ['client' => [...]]]]

This mechanism allows for intuitive organization where the file system structure directly maps to the configuration hierarchy.

Sources: src/ConfigFactory.php56-59

File Loading and Array Construction

Once the key is generated, the configuration file is loaded and nested using Hyperf\Collection\Arr::set():


Diagram: File Loading and Nested Array Construction

The process src/ConfigFactory.php54-62:

  1. Iterate Files: Loop through each file found by Finder
  2. Generate Key: Create dot-notation key from file path
  3. Load File: Use require to execute the PHP file
  4. Nest Structure: Use Arr::set() to create nested array with the generated key
  5. Collect Configs: Append each nested config to the results array

Sources: src/ConfigFactory.php54-62

Integration with Configuration Pipeline

The file-based configurations are integrated into the overall configuration loading pipeline within the __invoke() method:


Diagram: Integration with Configuration Loading Pipeline

The integration happens in __invoke() src/ConfigFactory.php22-33:

  1. Line 22: Load root config via readConfig()
  2. Line 23: Load autoload configs via readPaths()
  3. Line 26: Combine all sources: provider configs, root config, and autoload configs
  4. Lines 27-31: Merge using array_reduce() with ProviderConfig::mergeTwo()
  5. Line 33: Create Repository instance with merged result

The merge order ensures proper precedence: provider configs have lowest priority, followed by root config, with autoload configs having highest priority (applied last).

Sources: src/ConfigFactory.php22-33

File Discovery Configuration

The readPaths() method accepts two parameters that control the discovery process:

ParameterTypePurposeExample
$pathsarrayDirectories to scan[$configPath, $autoloadPath]
$excludesarrayFiles to exclude from scan['hyperf.php']

The exclusion mechanism prevents the root hyperf.php file from being loaded twice when scanning the config directory src/ConfigFactory.php23 as it's already loaded separately via readConfig() src/ConfigFactory.php22

Sources: src/ConfigFactory.php18-23 src/ConfigFactory.php46-53

Symfony Finder Configuration

The Symfony Finder component is configured with specific criteria for discovering configuration files:


Diagram: Symfony Finder Configuration Chain

The configuration chain src/ConfigFactory.php49-53:

  • Line 49: Create new Finder instance
  • Line 50: Configure for files (not directories) with .php extension in specified paths
  • Lines 51-53: Apply exclusions for each excluded filename

This ensures only relevant PHP configuration files are discovered, excluding the root configuration file to prevent duplicate loading.

Sources: src/ConfigFactory.php49-53

File Reading Safety

The readConfig() method implements defensive file reading with multiple safety checks:

  1. Existence Check: Verifies file exists before attempting to read
  2. Readability Check: Ensures file has read permissions
  3. Type Validation: Validates that the required file returns an array
  4. Default Fallback: Returns empty array if validation fails

This prevents errors during bootstrap if configuration files are missing or malformed src/ConfigFactory.php36-44

Sources: src/ConfigFactory.php36-44

Path Resolution

All file paths are resolved relative to the BASE_PATH constant:

  • Config Directory: BASE_PATH . '/config'
  • Root Config File: BASE_PATH . '/config/hyperf.php'
  • Autoload Directory: BASE_PATH . '/config/autoload'

The BASE_PATH constant is expected to be defined by the application bootstrap process and represents the application's root directory src/ConfigFactory.php15

Sources: src/ConfigFactory.php15-19

Code Entity Reference

The following table maps the system components discussed in this document to their code entities:

ComponentCode EntityFile LocationPurpose
Configuration FactoryConfigFactory classsrc/ConfigFactory.phpOrchestrates file-based config loading
Factory Entry Point__invoke() methodsrc/ConfigFactory.php:13-34Main configuration loading logic
Single File ReaderreadConfig() methodsrc/ConfigFactory.php:36-44Loads individual config file
Directory ScannerreadPaths() methodsrc/ConfigFactory.php:46-65Discovers and loads multiple files
File DiscoverySymfony\Component\Finder\Findersrc/ConfigFactory.php:49Locates PHP files in directories
Array NestingHyperf\Collection\Arr::set()src/ConfigFactory.php:60Creates nested array from dot key
Configuration MergingProviderConfig::mergeTwo()src/ConfigFactory.php:29Merges configuration arrays

Sources: src/ConfigFactory.php1-67