VOOZH about

URL: https://deepwiki.com/hypervel/translation/6-configuration-and-dependency-injection

⇱ Configuration and Dependency Injection | hypervel/translation | DeepWiki


Loading...
Menu

Configuration and Dependency Injection

Purpose and Scope

This document explains how the hypervel/translation package integrates with Hyperf's dependency injection (DI) container. It covers the ConfigProvider class that registers service bindings, the factory classes (TranslatorFactory and LoaderFactory) that instantiate translation components, and how configuration values are resolved during initialization.

For information about the specific contracts being instantiated, see Contracts and Interfaces. For details on how the Translator instance operates after initialization, see Core Translation System.

Package Registration with Hyperf

The package integrates with Hyperf through the composer.json extra configuration, which declares the ConfigProvider class as the integration point:


When Hyperf bootstraps, it discovers all packages with this configuration and invokes their respective ConfigProvider classes to collect dependency mappings, configuration values, and other service definitions.

Sources: composer.json40-43

ConfigProvider: Dependency Registration

The ConfigProvider class serves as the package's registration entry point. Its __invoke method returns an array containing dependency mappings that tell Hyperf's container how to resolve abstract contracts to concrete implementations:

ContractFactory
LoaderContract::classLoaderFactory::class
TranslatorContract::classTranslatorFactory::class

The ConfigProvider does not directly instantiate services. Instead, it registers factory classes that will be invoked lazily when the corresponding contract is first requested from the container.


Diagram: ConfigProvider Registration Flow - Code Entity Mapping

The ConfigProvider class implementation is minimal by design, delegating all instantiation logic to specialized factory classes:

src/ConfigProvider.php1-21

Sources: src/ConfigProvider.php1-21

Factory Pattern Architecture

The package uses the Factory Pattern to encapsulate the complex instantiation logic for translation services. This pattern provides several benefits:

  1. Centralized Configuration: All service configuration logic resides in dedicated factory classes
  2. Dependency Resolution: Factories can retrieve their dependencies from the container
  3. Lazy Instantiation: Services are only created when first requested
  4. Environment Awareness: Factories can adapt behavior based on runtime conditions

Diagram: Factory Pattern Implementation - Code Entity Mapping

Both factories follow the same pattern:

  1. Receive the ContainerInterface as a parameter
  2. Retrieve required dependencies from the container
  3. Instantiate and configure the target service
  4. Return the configured instance

Sources: src/LoaderFactory.php1-28 src/TranslatorFactory.php1-30

TranslatorFactory: Creating the Translator

The TranslatorFactory is responsible for instantiating and configuring the Translator class. It performs the following operations:

Dependency Resolution

DependencyRetrieval MethodReturn TypePurpose
ConfigInterface$container->get(ConfigInterface::class)ConfigInterfaceAccess application configuration via get() method
LoaderContract$container->get(LoaderContract::class)LoaderContractProvide translation data source (triggers LoaderFactory)

Configuration Values

Configuration KeyDefault ValueUsageFactory Code Reference
app.locale'en'Sets the translator's default locale$config->get('app.locale', 'en')
app.fallback_locale'en'Sets the fallback locale for missing translations$config->get('app.fallback_locale', 'en')

Instantiation Flow


Diagram: TranslatorFactory Instantiation Sequence

The factory implementation demonstrates the configuration of the Translator with both constructor injection (loader and primary locale) and method-based configuration (fallback locale):

src/TranslatorFactory.php14-29

Sources: src/TranslatorFactory.php1-30

LoaderFactory: Creating the File Loader

The LoaderFactory creates the FileLoader instance that reads translation files from the filesystem. This factory exhibits more complex logic to determine appropriate file paths.

Path Resolution Logic

The factory determines language file paths using conditional logic:


Diagram: LoaderFactory Path Resolution - Code Flow

Path Array Structure

The FileLoader constructor receives an array of two paths in priority order:

IndexPath ExpressionResolved ExamplePurpose
0dirname(__DIR__) . '/lang'/vendor/hypervel/translation/langPackage bundled translations (validation messages)
1$langPath variable/path/to/app/langApplication-specific translations and overrides

The FileLoader searches these paths in order when loading translation files, with later paths taking precedence for overrides.

The first path points to the package's own lang directory, which contains default translations (such as validation messages). The second path points to the application's language directory, allowing applications to override package translations or provide additional translations.

Type-Safe Path Detection

The factory uses an instanceof check against ApplicationContract to determine if the container provides a langPath() method. This enables the factory to work in different contexts:

  • Full Hypervel Application: Uses $container->langPath() to get the configured application language directory
  • Standalone/Testing Context: Falls back to BASE_PATH . '/lang' as a sensible default

Implementation details:

src/LoaderFactory.php14-27

Sources: src/LoaderFactory.php1-28

Configuration Sources and Hierarchies

The translation system retrieves configuration from multiple sources with a clear precedence order:

Application Configuration

Configuration values are retrieved via Hyperf's ConfigInterface, typically defined in the application's config/autoload/app.php:


These values are accessed with defaults:

Runtime Context Override

While not configured in the factories, the Translator class can override the locale at runtime via Hyperf's Context mechanism. The factory-configured locale serves as the default when no context override is present.

Path Configuration

ConfigurationSourceDefault ExpressionResolved ExampleConfigurable
Package lang pathHardcoded in LoaderFactorydirname(__DIR__) . '/lang'/vendor/hypervel/translation/langNo
Application lang pathApplicationContract::langPath()BASE_PATH . '/lang'/path/to/app/langVia langPath() method

Sources: src/TranslatorFactory.php1-30 src/LoaderFactory.php1-28

Complete Initialization Flow

The following diagram illustrates the complete sequence from container registration to a fully configured Translator instance:


Diagram: Complete Initialization Sequence

Key Phases

Bootstrap Phase (Steps 1-4)

  • Hyperf discovers the package via composer.json
  • ConfigProvider registers factory mappings
  • No services are instantiated yet

Resolution Phase (Steps 5-23)

  • Application requests TranslatorContract
  • Container invokes TranslatorFactory
  • Factory requests LoaderContract, triggering LoaderFactory
  • LoaderFactory creates FileLoader with path configuration
  • TranslatorFactory creates and configures Translator
  • Configured instance is cached in container

Singleton Behavior After the first resolution, the container caches the Translator instance. Subsequent requests return the same instance without invoking the factory again, ensuring consistent state throughout the application lifecycle.

Sources: composer.json40-43 src/ConfigProvider.php1-21 src/TranslatorFactory.php1-30 src/LoaderFactory.php1-28

Extending the Configuration

Applications can customize the translation system by:

  1. Providing Configuration Values: Set app.locale and app.fallback_locale in application config
  2. Implementing ApplicationContract: Provide custom langPath() implementation
  3. Replacing Factories: Override factory bindings in application ConfigProvider
  4. Replacing Loaders: Register custom LoaderContract implementation

Example custom factory registration:


Application-level dependency configurations take precedence over package-level configurations, allowing full customization without modifying package code.

Sources: src/ConfigProvider.php1-21