VOOZH about

URL: https://deepwiki.com/hypervel/translation/5.2-memory-based-loading

⇱ Memory-Based Loading | hypervel/translation | DeepWiki


Loading...
Menu

Memory-Based Loading

Purpose and Scope

This document covers the ArrayLoader class, which provides in-memory storage and retrieval of translation data. Unlike file-based loading (see 5.1), ArrayLoader stores translation messages directly in memory without any file system operations. This implementation is primarily used for testing scenarios, runtime translation injection, and situations where translations are generated dynamically rather than loaded from disk.

Architecture Overview

The ArrayLoader implements the Loader contract interface, providing an alternative to FileLoader for scenarios where translations should not be read from the file system.

Diagram: ArrayLoader in the Translation Loading System


Sources: src/ArrayLoader.php1-66

Data Structure

The ArrayLoader maintains a single protected property $messages that stores all translation data in a nested array structure.

Storage Hierarchy

LevelKeyDescription
1NamespacePackage/namespace identifier, or '*' for default namespace
2LocaleLanguage code (e.g., 'en', 'es', 'fr')
3GroupTranslation group/file name (e.g., 'messages', 'validation')
4KeysTranslation key-value pairs

Example Structure

$messages = [
 '*' => [
 'en' => [
 'messages' => [
 'welcome' => 'Welcome',
 'goodbye' => 'Goodbye'
 ],
 'validation' => [
 'required' => 'The :attribute field is required.'
 ]
 ],
 'es' => [
 'messages' => [
 'welcome' => 'Bienvenido',
 'goodbye' => 'Adiós'
 ]
 ]
 ],
 'admin' => [
 'en' => [
 'dashboard' => [
 'title' => 'Admin Dashboard'
 ]
 ]
 ]
]

Sources: src/ArrayLoader.php11-14

Core Methods

load()

Diagram: Translation Resolution Flow


The load() method retrieves translation messages for a specific locale and group. It accepts an optional namespace parameter, defaulting to '*' for the global namespace.

Method Signature

public function load(string $locale, string $group, ?string $namespace = null): array

Parameters:

  • $locale - The language code to load (e.g., 'en', 'es')
  • $group - The translation group name (e.g., 'messages', 'validation')
  • $namespace - Optional namespace for package-specific translations

Return Value: Array of translation key-value pairs, or empty array if not found

Implementation Details:

Sources: src/ArrayLoader.php16-24

addMessages()

The addMessages() method programmatically adds translation data to the loader's internal storage.

Method Signature

public function addMessages(string $locale, string $group, array $messages, ?string $namespace = null): static

Parameters:

  • $locale - Target language code
  • $group - Translation group name
  • $messages - Array of translation key-value pairs
  • $namespace - Optional namespace (defaults to '*')

Return Value: Returns $this for method chaining

Implementation: The method directly assigns the entire $messages array to the appropriate nested location in the storage hierarchy src/ArrayLoader.php54 completely replacing any existing translations for that namespace/locale/group combination.

Usage Example:


Sources: src/ArrayLoader.php47-57

Stub Implementations

The ArrayLoader includes stub implementations for path and namespace management methods required by the Loader contract. These methods do nothing, as ArrayLoader does not interact with the file system.

MethodPurpose (in FileLoader)ArrayLoader Implementation
addNamespace()Registers package translation pathsEmpty method body src/ArrayLoader.php29-31
addJsonPath()Registers JSON file directoriesEmpty method body src/ArrayLoader.php36-38
addPath()Registers PHP file directoriesEmpty method body src/ArrayLoader.php43-45
namespaces()Returns registered namespacesReturns empty array src/ArrayLoader.php62-65

These stub implementations satisfy the Loader contract interface while maintaining the in-memory-only nature of the ArrayLoader.

Sources: src/ArrayLoader.php27-65

Use Cases

Testing

The primary use case for ArrayLoader is in test environments where translations need to be controlled precisely without creating physical translation files.

Benefits in Testing:

  • No file I/O overhead - Tests run faster without disk access
  • Isolation - Each test can have its own translation set without affecting others
  • Simplicity - Translations defined inline in test code
  • Flexibility - Easy to test edge cases with specific translation values

Example Test Scenario:


Runtime Translation Injection

ArrayLoader enables dynamic translation addition during application runtime, useful for:

  • Database-driven translations - Load translations from a database at runtime
  • User-generated content - Allow administrators to add translations through an interface
  • A/B testing - Inject different translation variants for testing
  • Plugin systems - Dynamically add translations when plugins are loaded

Mock Implementations

In development or staging environments, ArrayLoader can provide placeholder translations before actual translation files are created.

Sources: src/ArrayLoader.php1-66

Comparison with FileLoader

Key Differences

AspectArrayLoaderFileLoader
StorageIn-memory arrayFile system (PHP/JSON files)
PerformanceFastest access (no I/O)Slower (disk reads, but cached)
PersistenceLost on process endPersists between requests
Typical UseTesting, runtime injectionProduction applications
Data VolumeLimited by memoryLimited by disk space
Namespace SupportLogical (storage only)Physical (directory paths)
Path ManagementNot applicable (stub methods)Full support with hints
JSON SupportManual (via addMessages)Automatic file loading

Diagram: Implementation Comparison


When to Use ArrayLoader:

  1. Unit tests requiring precise translation control
  2. Integration tests that shouldn't touch the file system
  3. Runtime translation modifications
  4. Temporary or ephemeral translation needs
  5. Mock implementations during development

When to Use FileLoader:

  1. Production applications (see 5.1)
  2. Persistent translation storage
  3. Standard Laravel/Hyperf translation file structure
  4. Package distribution with translation files
  5. Translation file management by non-developers

Sources: src/ArrayLoader.php1-66

Integration with Translator

The Translator class uses the Loader contract interface, meaning it can work with either ArrayLoader or FileLoader interchangeably. The loader implementation is typically determined by the LoaderFactory during dependency injection (see 6).

Diagram: Translator and ArrayLoader Interaction


The Translator never directly knows whether it's using ArrayLoader or FileLoader - it only depends on the Loader contract interface. This enables seamless switching between implementations based on the execution context (production vs. testing).

Sources: src/ArrayLoader.php1-66

Memory Considerations

Since ArrayLoader stores all translations in memory, consider the following:

Memory Usage Factors:

  • Number of locales loaded
  • Number of translation groups per locale
  • Size of translation arrays
  • Number of namespaces

Typical Memory Footprint:

  • Small test suite: ~1-10 KB per locale/group
  • Medium application: ~100-500 KB for complete translations
  • Large application: 1-5 MB for multiple locales with extensive translations

Best Practices:

  1. Use ArrayLoader only for the translations actually needed in each test
  2. Avoid loading entire application translation sets in memory unnecessarily
  3. Consider using FileLoader with caching for large translation sets
  4. Clear the ArrayLoader instance between tests if reusing

Sources: src/ArrayLoader.php11-14