VOOZH about

URL: https://deepwiki.com/hypervel/translation/4.2-loader-contract

⇱ Loader Contract | hypervel/translation | DeepWiki


Loading...
Menu

Loader Contract

Purpose and Scope

This document describes the Loader contract, which defines the interface for loading translation data from various sources in the Hypervel Translation package. The contract establishes a standard set of methods that all loader implementations must provide, enabling the translation system to retrieve messages without coupling to specific data sources.

For detailed information about specific loader implementations, see File-Based Loading and Memory-Based Loading. For information about how the Translator uses loaders, see Core Translation System.

Sources: src/Contracts/Loader.php1-36


Interface Definition

The Loader contract is defined in the Hypervel\Translation\Contracts namespace and extends Hyperf's TranslatorLoaderInterface. This inheritance ensures compatibility with the broader Hyperf ecosystem while adding Hypervel-specific functionality.


The contract defines five core methods and one accessor method that loader implementations must provide:

MethodReturn TypePurpose
load()arrayRetrieve translation messages for a specific locale, group, and namespace
addNamespace()voidRegister a namespace with its corresponding filesystem hint
addJsonPath()voidRegister a directory path for JSON translation files
addPath()voidRegister a directory path for PHP translation files
namespaces()arrayRetrieve all registered namespaces

Sources: src/Contracts/Loader.php9-35


Contract Architecture

The following diagram illustrates how the Loader contract fits into the translation system's architecture and its relationship with Hyperf's base interface:


Diagram: Loader Contract in System Architecture

The Loader contract acts as an abstraction layer between the Translator class and concrete data sources. By programming against this interface, the Translator remains agnostic to whether translations come from files, memory, databases, or other sources.

Sources: src/Contracts/Loader.php9 src/FileLoader.php12 src/ArrayLoader.php9 Diagram 4 from high-level architecture


Method Specifications

load()

The primary method for retrieving translation messages. This method accepts three parameters that identify the specific set of translations to load:


Parameters:

ParameterTypeDescription
$localestringThe language code (e.g., 'en', 'es', 'fr')
$groupstringThe translation group/file name (e.g., 'validation', 'messages')
$namespacestring|nullOptional namespace identifier for namespaced translations

Return Value: An associative array containing translation key-value pairs. Returns an empty array if no translations are found.

Special Cases:

  • When $group === '*' and $namespace === '*', the loader should return JSON translations
  • When $namespace is null or '*', the loader should return standard (non-namespaced) translations
  • When a $namespace is provided, the loader should return namespaced translations

Sources: src/Contracts/Loader.php14 src/FileLoader.php46-57 src/ArrayLoader.php19-24


addNamespace()

Registers a namespace with its corresponding filesystem hint. Namespaces enable modular translation organization, typically used by packages to provide their own translation files.


Parameters:

ParameterTypeDescription
$namespacestringThe namespace identifier (e.g., 'validation', 'admin')
$hintstringThe filesystem path where the namespace's translations are located

Usage Pattern: Namespaces are typically used to allow packages to bundle translations that can be referenced using double-colon syntax (e.g., validation::messages.required). The hint provides the base path where the namespace's translation files reside.

Sources: src/Contracts/Loader.php19 src/FileLoader.php131-134


addJsonPath()

Registers a directory path where JSON translation files are located. JSON translations provide a flat key-value structure for simple translation scenarios.


Parameters:

ParameterTypeDescription
$pathstringAbsolute path to a directory containing JSON translation files

File Structure: JSON files should be named using locale codes (e.g., en.json, es.json) and contain flat key-value pairs:


Sources: src/Contracts/Loader.php24 src/FileLoader.php155-158


addPath()

Registers a directory path where PHP translation files are organized in locale subdirectories. This is the standard method for structured translations.


Parameters:

ParameterTypeDescription
$pathstringAbsolute path to a directory containing locale subdirectories

Expected Directory Structure:

{path}/
 en/
 messages.php
 validation.php
 es/
 messages.php
 validation.php

Sources: src/Contracts/Loader.php29 src/FileLoader.php147-150


namespaces()

Returns an associative array of all registered namespaces and their corresponding filesystem hints.


Return Value: An associative array where keys are namespace identifiers and values are their filesystem paths.

Example Return:


Sources: src/Contracts/Loader.php34 src/FileLoader.php139-142 src/ArrayLoader.php62-65


Translation Loading Flow

The following diagram illustrates how the Translator interacts with a Loader implementation during a translation request:


Diagram: Translation Loading Sequence

The Translator calls the load() method on the Loader interface without knowledge of which concrete implementation is being used. The loader implementation determines how to retrieve the requested translations based on its internal configuration.

Sources: src/Translator.php524-549 (referenced from high-level diagrams), src/Contracts/Loader.php14


Implementation Comparison

The package provides two implementations of the Loader contract, each suited for different use cases:

FeatureFileLoaderArrayLoader
Data SourceFilesystem (PHP/JSON files)In-memory array
PersistencePersistent across requestsEphemeral (request-scoped)
PerformanceI/O overhead on first load, cached afterImmediate access, no I/O
Use CasesProduction applications, standard translationsTesting, runtime-added translations
Namespace SupportFull support with override mechanismNo-op implementation
Path ManagementManages multiple paths and JSON pathsNo-op implementation
ConfigurationRequires filesystem dependencyNo external dependencies

Implementation Details:

  • FileLoader: Implements all contract methods with full functionality. See File-Based Loading for detailed documentation.
  • ArrayLoader: Implements the load() method but provides no-op implementations for path and namespace management methods. See Memory-Based Loading for detailed documentation.

Sources: src/FileLoader.php12-175 src/ArrayLoader.php9-66


Usage in Dependency Injection

The Loader contract is registered in Hyperf's dependency injection container through the ConfigProvider. Applications can type-hint the contract to receive the configured implementation:


Diagram: Loader Contract Resolution in DI Container

The LoaderFactory is responsible for instantiating the appropriate loader implementation based on application configuration. By default, it creates a FileLoader with paths determined from the application's language directory configuration.

Sources: src/ConfigProvider.php1-45 (referenced from high-level diagrams), src/LoaderFactory.php1-50 (referenced from high-level diagrams)


Extension Points

The Loader contract can be implemented by custom classes to support alternative translation sources:

Potential Custom Implementations:

  • DatabaseLoader: Load translations from a database table
  • ApiLoader: Fetch translations from a remote API
  • CachedLoader: Wrap another loader with Redis/Memcached caching
  • CompositeLoader: Aggregate multiple loaders with fallback logic

Implementation Requirements:

  1. Implement all methods defined in the contract
  2. Return empty arrays or no-op for unsupported operations
  3. Ensure thread-safety if used in concurrent contexts
  4. Register the custom implementation in the DI container

Sources: src/Contracts/Loader.php9-35


Contract Compliance

Implementations of the Loader contract must adhere to the following behavioral contracts:

Method Signatures:

  • All methods must match the exact signatures defined in the interface
  • Return types must be strictly enforced (PHP 8.2+ strict typing)

Load Method Guarantees:

  • Must return an array (never null)
  • Must return an empty array if translations are not found
  • Must not throw exceptions for missing translations
  • Must handle special cases for JSON loading ($group === '*' and $namespace === '*')

Path Methods:

  • addPath(), addJsonPath(), and addNamespace() should be idempotent
  • Multiple calls with the same path should not cause errors
  • Paths should be stored in registration order for precedence

Namespace Method:

  • namespaces() must return an associative array
  • Should return an empty array if no namespaces are registered

Sources: src/Contracts/Loader.php9-35 src/FileLoader.php46-57 src/ArrayLoader.php19-24