VOOZH about

URL: https://deepwiki.com/hypervel/translation/8-advanced-features

⇱ Advanced Features | hypervel/translation | DeepWiki


Loading...
Menu

Advanced Features

This document provides an overview of advanced functionality in the hypervel/translation package beyond basic translation retrieval. These features enable deferred translation evaluation, integration with validation systems, and entity-specific locale preferences.

For core translation operations, see Core Translation System. For global helper functions, see Global Helper Functions. For pluralization, see Message Selection and Pluralization.

Overview

The translation package includes three advanced feature categories that extend the basic translation capabilities:

FeaturePrimary Class/InterfaceUse Case
Deferred TranslationsPotentiallyTranslatedStringDelay translation evaluation until string conversion
Validation IntegrationCreatesPotentiallyTranslatedStrings traitManage validation message lifecycle with automatic cleanup
Locale PreferencesHasLocalePreference interfaceEnable entity-specific locale resolution

These features are designed for specialized scenarios where the standard translation flow requires customization or optimization.

Sources: src/PotentiallyTranslatedString.php1-73 src/CreatesPotentiallyTranslatedStrings.php1-46 src/Contracts/HasLocalePreference.php1-13

Component Architecture


Diagram: Advanced Feature Integration

This diagram illustrates how advanced features integrate with the core Translator class. PotentiallyTranslatedString depends on the Translator contract for actual translation work. The CreatesPotentiallyTranslatedStrings trait creates specialized instances of PotentiallyTranslatedString for validation scenarios. The HasLocalePreference interface is implemented by domain entities to provide locale information to the translator.

Sources: src/PotentiallyTranslatedString.php1-73 src/CreatesPotentiallyTranslatedStrings.php1-46 src/Contracts/HasLocalePreference.php1-13

Deferred Translation System

The PotentiallyTranslatedString class enables lazy evaluation of translation strings. Instead of immediately translating a key, the system creates an object that holds the translation key and performs the actual translation only when the string value is needed.

Core Mechanism


Diagram: Deferred Translation Lifecycle

The translation key is stored upon object creation but translation is deferred until string conversion. The translate() or translateChoice() methods can be called explicitly to trigger translation, or it occurs automatically when the object is cast to string via __toString().

Sources: src/PotentiallyTranslatedString.php11-73

Key Methods

The PotentiallyTranslatedString class provides these core methods:

MethodSignaturePurpose
translatetranslate(array $replace = [], ?string $locale = null): staticExplicitly translate using Translator::get()
translateChoicetranslateChoice(array|Countable|float|int $number, array $replace = [], ?string $locale = null): staticExplicitly translate with pluralization
originaloriginal(): stringRetrieve the original untranslated key
toStringtoString(): stringGet the translated string or original if not translated
__toString__toString(): stringAutomatic string conversion for type coercion

The class implements Stringable to enable automatic type conversion. The internal $translation property src/PotentiallyTranslatedString.php16 caches the result after the first translation to avoid redundant translator calls.

Sources: src/PotentiallyTranslatedString.php11-73

Validation Integration Trait

The CreatesPotentiallyTranslatedStrings trait extends deferred translation for validation scenarios where messages must be collected into a message bag with automatic lifecycle management.

Anonymous Class Pattern


Diagram: Validation Message Lifecycle

The trait creates an anonymous class that extends PotentiallyTranslatedString and adds a destructor. When the object goes out of scope, the destructor automatically adds the translated message to the validator's message collection.

Sources: src/CreatesPotentiallyTranslatedStrings.php10-46

Destructor Behavior

The method pendingPotentiallyTranslatedString() src/CreatesPotentiallyTranslatedStrings.php15-45 creates instances with custom destructors:

ConditionDestructor ActionLocation in Messages Array
$message === null$this->messages[] = $messageAppended to array
$message !== null$this->messages[$attribute] = $messageKeyed by attribute name

The anonymous class src/CreatesPotentiallyTranslatedStrings.php21-44 stores a Closure $destructor property that is invoked when the object is destroyed. The destructor calls toString() to force translation evaluation before adding the message to the collection.

Sources: src/CreatesPotentiallyTranslatedStrings.php15-45

Integration Example Flow


Diagram: Validation Message Deferred Translation Flow

The validator creates a deferred translation object that holds the message key. When the object destructs at the end of its scope, it translates the message and automatically adds it to the validator's message collection. This pattern ensures messages are only translated if they are actually needed.

Sources: src/CreatesPotentiallyTranslatedStrings.php15-45 src/PotentiallyTranslatedString.php62-72

Entity Locale Preferences

The HasLocalePreference interface enables domain entities to specify their preferred locale, allowing the translator to respect user-specific language settings.

Interface Definition

The interface defines a single method src/Contracts/HasLocalePreference.php8-12:

public function preferredLocale(): ?string

Returns the entity's preferred locale string (e.g., 'en', 'es', 'fr') or null if no preference exists.

Sources: src/Contracts/HasLocalePreference.php1-13

Integration with Translator


Diagram: Locale Resolution with HasLocalePreference

When translating, the Translator checks if any replacement values implement HasLocalePreference. If found and no explicit locale is specified, the entity's preferred locale is used. This enables user-specific translations without explicitly passing locale parameters throughout the application.

Sources: src/Contracts/HasLocalePreference.php1-13

Implementation Pattern

Domain entities implement the interface to provide locale preferences:

Entity TypeImplementation Pattern
User modelsReturn user's language preference from database field
Organization modelsReturn organization's default language
Tenant modelsReturn tenant-specific locale configuration
Session objectsReturn current session's locale setting

The translator automatically detects implementations when processing replacements, enabling context-aware translations without modifying translation calls throughout the codebase.

Sources: src/Contracts/HasLocalePreference.php7-12

Feature Comparison Matrix

FeatureTranslation TimingUse CaseRequires Special Setup
Standard TranslationImmediateGeneral translation needsNo
PotentiallyTranslatedStringDeferred until string conversionDelayed evaluation, optional translationNo
CreatesPotentiallyTranslatedStringsDeferred until object destructionValidation messages with automatic cleanupYes - trait must be used
HasLocalePreferenceNormal translator timingUser-specific locales without explicit parametersYes - entities must implement interface

Sources: src/PotentiallyTranslatedString.php1-73 src/CreatesPotentiallyTranslatedStrings.php1-46 src/Contracts/HasLocalePreference.php1-13

Advanced Feature Relationships


Diagram: Advanced Feature Layer

Advanced features build upon the basic translation system. PotentiallyTranslatedString wraps translation calls for deferred evaluation. CreatesPotentiallyTranslatedStrings specializes deferred translation for validation use cases. HasLocalePreference enhances standard translation by providing entity-specific locale resolution.

Sources: src/PotentiallyTranslatedString.php1-73 src/CreatesPotentiallyTranslatedStrings.php1-46 src/Contracts/HasLocalePreference.php1-13

Related Documentation

For detailed information about each advanced feature:

Sources: src/PotentiallyTranslatedString.php1-73 src/CreatesPotentiallyTranslatedStrings.php1-46 src/Contracts/HasLocalePreference.php1-13