VOOZH about

URL: https://deepwiki.com/hypervel/translation/8.1-lazy-translation-with-potentiallytranslatedstring

⇱ Lazy Translation with PotentiallyTranslatedString | hypervel/translation | DeepWiki


Loading...
Menu

Lazy Translation with PotentiallyTranslatedString

Purpose and Scope

This document covers the PotentiallyTranslatedString class, which implements deferred (lazy) translation functionality in the hypervel/translation package. This class allows translation strings to be created and stored without immediate translation, deferring the actual translation operation until explicitly invoked or when the string is cast to a string.

For information about the core translation system and immediate translation, see Core Translation System. For information about how this class is created and used in validation contexts, see CreatesPotentiallyTranslatedStrings Trait. For pluralization details, see Message Selection and Pluralization.


Lazy Translation Pattern

The PotentiallyTranslatedString class implements a lazy evaluation pattern for translations. Unlike immediate translation via the Translator class where translation occurs at the point of call, this class defers translation until one of the following occurs:

  1. Explicit call to translate() or translateChoice() methods
  2. String coercion via __toString() when no translation has been performed
  3. Explicit call to toString() method

This pattern is particularly useful in scenarios where:

  • Translation keys need to be stored for later processing
  • The locale may change between creation and rendering
  • Translation is optional or conditional
  • Performance optimization requires deferring translation operations

Sources: src/PotentiallyTranslatedString.php1-73


Class Structure and Dependencies


Properties

PropertyTypeInitial ValuePurpose
$stringstringConstructor parameterThe original translation key or string to be translated
$translatorTranslatorConstructor parameterThe translator instance used to perform translations
$translation?stringnullCached translated string after translate() or translateChoice() is called

Key Characteristics

  • Immutability of Source: The original $string property is never modified
  • State Tracking: The $translation property tracks whether translation has occurred
  • Translator Dependency: Requires a Translator instance injected at construction
  • Fluent Interface: Translation methods return $this for method chaining

Sources: src/PotentiallyTranslatedString.php11-28


Object Lifecycle


State 1: Untranslated (Initial State)

When a PotentiallyTranslatedString is constructed:

  • $string holds the translation key (e.g., "validation.required")
  • $translator holds the injected Translator instance
  • $translation is null
  • Calling __toString() returns $string (the original key)

Code Reference: src/PotentiallyTranslatedString.php24-28

State 2: Translated

After calling translate():

  • $translation is populated with the result from $translator->get()
  • Calling __toString() returns $translation
  • The original $string remains accessible via original()

Code Reference: src/PotentiallyTranslatedString.php33-38

State 3: Translated with Pluralization

After calling translateChoice():

  • $translation is populated with the result from $translator->choice()
  • Pluralization rules are applied based on the provided number
  • Calling __toString() returns the pluralized $translation

Code Reference: src/PotentiallyTranslatedString.php43-48

Sources: src/PotentiallyTranslatedString.php11-73


Translation Methods

translate() Method


The translate() method performs standard translation without pluralization.

Method Signature:

public function translate(array $replace = [], ?string $locale = null): static

Parameters:

  • $replace: Array of placeholder replacements (e.g., [':name' => 'John'])
  • $locale: Optional locale override (uses current locale if null)

Behavior:

Sources: src/PotentiallyTranslatedString.php33-38


translateChoice() Method


The translateChoice() method performs translation with pluralization based on a count.

Method Signature:

public function translateChoice(array|Countable|float|int $number, array $replace = [], ?string $locale = null): static

Parameters:

  • $number: Numeric count determining plural form (accepts int, float, array, or Countable)
  • $replace: Array of placeholder replacements
  • $locale: Optional locale override

Behavior:

Sources: src/PotentiallyTranslatedString.php43-48


Stringable Interface Implementation

__toString() Magic Method

The __toString() method enables automatic string coercion in string contexts.

Method Signature:

public function __toString(): string

Return Value:

  • Returns $translation if it has been set (not null)
  • Otherwise returns $string (the original untranslated key)

Code Logic: src/PotentiallyTranslatedString.php61-64


This null coalescing operator ensures that untranslated instances return their original key, while translated instances return the translated value.

Sources: src/PotentiallyTranslatedString.php61-64


toString() Method

The toString() method provides an explicit alternative to __toString().

Method Signature:

public function toString(): string

Behavior:

  • Casts the object to string using (string) $this
  • Internally calls __toString()
  • Useful when explicit method calls are preferred over magic methods

Sources: src/PotentiallyTranslatedString.php69-72


original() Method

The original() method provides access to the untranslated string.

Method Signature:

public function original(): string

Return Value:

  • Always returns $string (the original translation key)
  • Returns the same value regardless of translation state

Use Cases:

  • Debugging: inspecting the original translation key
  • Logging: storing the key for later analysis
  • Fallback: using the key when translation is undesirable

Sources: src/PotentiallyTranslatedString.php53-56


Usage Patterns

Pattern 1: Deferred Translation


Example Scenario: A validation system creates PotentiallyTranslatedString instances for error messages during validation. The actual translation is deferred until the messages are rendered in the user's locale.

Sources: src/PotentiallyTranslatedString.php1-73


Pattern 2: Conditional Translation

ScenarioTranslation StateOutput
Translation key exists in localeTranslatedLocalized string
Translation key missing (returns key)Untranslated fallbackOriginal key as string
Object never translatedUntranslatedOriginal key as string

This pattern allows the object to gracefully handle missing translations by falling back to the original key.


Pattern 3: Method Chaining


The fluent interface allows chaining translation and string conversion operations.

Sources: src/PotentiallyTranslatedString.php33-48


Comparison: translate() vs translateChoice()

Aspecttranslate()translateChoice()
PurposeSimple key-value translationPluralization-aware translation
Underlying MethodTranslator::get()Translator::choice()
Number ParameterNot requiredRequired (first parameter)
PluralizationNo plural form selectionApplies locale-specific plural rules
Inline ConditionsNot processedProcesses {n} and [n,m] syntax
:count InjectionManual via $replace arrayAutomatic injection of :count
Use CaseStatic messages, greetingsItem counts, time durations

Sources: src/PotentiallyTranslatedString.php33-48


Integration with Translation System


The PotentiallyTranslatedString class acts as a proxy between the application layer and the translation system, allowing translation operations to be deferred and controlled programmatically.

Key Integration Points:

Sources: src/PotentiallyTranslatedString.php1-73


Memory and Performance Considerations

Memory Characteristics

PropertyMemory ImpactNotes
$stringMinimal (single string)Always stored
$translatorReference onlyShared singleton instance
$translationMinimal (single string)Only allocated after translation

Performance Characteristics

  • Lazy Evaluation: Translation is deferred until needed, avoiding unnecessary work
  • Single Translation: Once translated, the result is cached in $translation
  • No Re-translation: Subsequent __toString() calls use cached value
  • Reference Sharing: The $translator property holds a reference to the shared singleton

Best Practices

  1. Defer translation until the locale is definitively known
  2. Avoid premature translation in constructors or early initialization
  3. Cache instances when multiple string coercions are expected
  4. Use original() for debugging without triggering translation

Sources: src/PotentiallyTranslatedString.php1-73


State Management Summary


The class maintains three distinct pieces of state, with clear separation between the immutable original string, the shared translator service, and the mutable translation cache.

Sources: src/PotentiallyTranslatedString.php11-73