Oihana PHP

initDefinitions.php

Table of Contents

Functions

initDefinitions()  : array<string|int, mixed>
Initialize all DI container definitions by loading and merging PHP definition files.

Functions

initDefinitions()

Initialize all DI container definitions by loading and merging PHP definition files.

initDefinitions(string $basePath[, bool $recursive = true ]) : array<string|int, mixed>

This function scans $basePath recursively for .php files, requires each file, and merges the resulting arrays into a single definitions array. It is intended to assemble service definitions for a DI container.

Behavior:

  • Only files with the "php" extension are considered.
  • Files are discovered recursively in subdirectories.
  • Each file must return an array; non-array returns may cause merge issues or exceptions in requireAndMergeArrays.
  • The arrays are merged deeply by default : when two files carry the same key and both values are arrays, the arrays are merged key by key, recursively. With $recursive set to false, the merge is flat : the value of the last file wins, whatever its type. A flat merge is the right one for container definitions, where a key is an entry and the last definition of an entry replaces the previous one, as PHP-DI itself does with several sources ; it is also far cheaper, since a deep merge copies the whole accumulated array at every file.
Parameters
$basePath : string

Absolute or relative path to the root directory containing definition files.

$recursive : bool = true

Merge the arrays deeply (default) ; false merges them flat, the last value of a key wins.

Tags
throws
Exception

If a required file cannot be read/included or merging fails.

see
recursiveFilePaths()
requireAndMergeArrays()
initContainer()
example
use DI\ContainerBuilder;
use function oihana\init\initDefinitions;

// Load all container definitions from the 'definitions' directory
$definitions = initDefinitions(__DIR__ . '/../../definitions');

// The same, merged flat : the last definition of an entry wins, and nothing is merged deeply
$definitions = initDefinitions(__DIR__ . '/../../definitions', recursive: false);

// Example: pass the definitions to your container builder
$containerBuilder = new ContainerBuilder() ;

$containerBuilder->addDefinitions( $definitions ) ;

$containerBuilder->build() ;
Return values
array<string|int, mixed> —

Merged definitions array.

On this page

Search results