VOOZH about

URL: https://deepwiki.com/hypervel/translation/3-global-helper-functions

⇱ Global Helper Functions | hypervel/translation | DeepWiki


Loading...
Menu

Global Helper Functions

Purpose and Scope

This page documents the three global helper functions provided by the hypervel/translation package that offer convenient, procedural-style access to translation functionality. These functions serve as syntactic sugar for retrieving the Translator instance from the dependency injection container and calling its methods.

For detailed information about the underlying Translator class and its methods, see Core Translation System. For information about the dependency injection configuration that makes these helpers work, see Configuration and Dependency Injection.


Overview

The translation system provides three global helper functions defined in src/Functions.php:

FunctionPurposeDelegate Method
__()Translate a message keyTranslator::trans()
trans()Translate a message key or return Translator instanceTranslator::get()
trans_choice()Translate with pluralization based on countTranslator::transChoice()

All three functions follow the same resolution pattern: they retrieve the TranslatorContract implementation from the Hyperf application container and delegate to the appropriate translator method.

Sources: src/Functions.php1-47


Helper Function Resolution Mechanism


Resolution Process:

  1. Container Retrieval: Each helper calls ApplicationContext::getContainer() to access the Hyperf dependency injection container src/Functions.php16-44
  2. Contract Resolution: The container is queried for TranslatorContract::class src/Functions.php17-44
  3. Singleton Instance: The container returns the configured Translator singleton (registered via TranslatorFactory)
  4. Method Delegation: The helper delegates to the appropriate Translator method
  5. Return Value: The translated string (or translator instance for trans() with null key) is returned to the caller

This resolution happens on every call, but the container caches the singleton Translator instance, so performance impact is minimal.

Sources: src/Functions.php14-46


Function Reference

The __() Function


Purpose: Primary translation helper for simple message retrieval.

Parameters:

  • $key - Translation key in group.item or namespace::group.item format (nullable)
  • $replace - Associative array of placeholder replacements (default: [])
  • $locale - Target locale, uses current locale if null (default: null)

Return Value:

  • Translated string with replacements applied
  • Array if the translation key resolves to nested translations
  • null if $key is null

Implementation:

The __() function is the most straightforward helper. It resolves the translator from the container and calls Translator::trans(), which internally delegates to Translator::get() src/Functions.php14-19


Typical Usage:


Sources: src/Functions.php11-19 src/Translator.php489-494


The trans() Function


Purpose: Translation helper with dual behavior - returns translator instance when called with no key, or translated message otherwise.

Parameters:

  • $key - Translation key in group.item or namespace::group.item format (nullable)
  • $replace - Associative array of placeholder replacements (default: [])
  • $locale - Target locale, uses current locale if null (default: null)

Return Value:

  • TranslatorContract instance if $key is null
  • Translated string with replacements applied if $key is provided
  • Array if the translation key resolves to nested translations

Implementation:

The trans() function has special behavior when called without arguments src/Functions.php26-36 Note that there is a bug in the implementation: when $key is null, the function retrieves the translator but doesn't return it src/Functions.php28-31


Typical Usage:


Differences from __():

Aspect__()trans()
Method calledTranslator::trans()Translator::get()
Null key behaviorReturns nullIntended to return Translator instance (buggy)
Primary use caseSimple translationsTranslations or accessing translator

Sources: src/Functions.php21-36 src/Translator.php489-494


The trans_choice() Function


Purpose: Translation helper for pluralized messages based on a numeric count.

Parameters:

  • $key - Translation key pointing to a pluralized message (required)
  • $number - Count value determining plural form. Accepts:
    • int or float - Direct numeric value
    • array - Count of array elements is used
    • Countable - Result of count() is used
  • $replace - Associative array of placeholder replacements (default: [])
  • $locale - Target locale for pluralization rules (default: null)

Return Value: Pluralized translated string with replacements applied

Implementation:

The trans_choice() function delegates to Translator::transChoice(), which internally calls Translator::choice() src/Functions.php41-46 The choice() method handles count extraction, pluralization via MessageSelector, and placeholder replacement.


Automatic :count Replacement:

The choice() method automatically adds the count value to the replacement array with key 'count' if not already present src/Translator.php181-183 This allows translation strings to reference the count using the :count placeholder.

Typical Usage:


Pluralization Rules:

The actual pluralization logic is handled by MessageSelector, which implements locale-specific rules for 150+ languages. For details on how pluralization works, see Message Selection and Pluralization.

Sources: src/Functions.php38-46 src/Translator.php501-504 src/Translator.php166-189


Code Entity Mapping


Entity Reference Table:

Code EntityFilePurpose
__()src/Functions.php14-19Global helper for basic translation
trans()src/Functions.php26-36Global helper with dual behavior
trans_choice()src/Functions.php41-46Global helper for pluralization
ApplicationContextHyperf FrameworkProvides access to DI container
TranslatorContractsrc/Contracts/Translator.phpInterface defining translator contract
Translatorsrc/Translator.phpMain translation service implementation
Translator::trans()src/Translator.php491-494Delegates to get()
Translator::get()src/Translator.php115-161Core translation retrieval method
Translator::transChoice()src/Translator.php501-504Delegates to choice()
Translator::choice()src/Translator.php166-189Pluralization method

Sources: src/Functions.php1-47 src/Translator.php489-505


Helper Function Comparison

Feature__()trans()trans_choice()
Return with null keynullTranslatorContract (buggy)N/A (key required)
Underlying methodtrans()get()get()transChoice()choice()
Pluralization support❌ No❌ No✅ Yes
Count parameter❌ No❌ No✅ Required
Auto :count injection❌ No❌ No✅ Yes
Array/Countable support❌ No❌ No✅ Yes (auto-counts)
Primary use caseQuick translations in viewsGeneral translation, accessing translatorItems with quantities
PSR compatibilityStandard functionStandard functionStandard function

Sources: src/Functions.php1-47 src/Translator.php489-505


Resolution and Performance Considerations

Container Resolution Cost

Each helper function call resolves the translator from the container:


Performance Impact:

  • Container lookup: O(1) hash table lookup
  • Singleton pattern: Translator instance created once per request context
  • Translation caching: Loaded translation files cached in $loaded array src/Translator.php32

The resolution overhead is minimal because:

  1. The container returns the same singleton instance on repeated calls
  2. Translation files are loaded once and cached
  3. No new object instantiation occurs after initial resolution

When to Use Helpers vs. Direct Injection

Use Helper Functions When:

  • Writing view templates or simple procedural code
  • Need quick, one-off translations
  • Context doesn't support dependency injection
  • Following framework conventions (e.g., Laravel-style blade templates)

Use Direct Injection When:

  • Building service classes with multiple translation calls
  • Need to mock translator in tests
  • Require access to translator methods beyond get(), choice(), and locale management
  • Following strict dependency injection principles

Sources: src/Functions.php14-46 src/Translator.php69-74


Relationship to Core Systems


Integration Points:

  1. Helpers to Container: All helpers use ApplicationContext::getContainer() src/Functions.php16-43
  2. Container to Contract: Container resolves TranslatorContract::class to Translator instance
  3. Translator to Loader: Translator uses injected Loader to load translation files src/Translator.php70
  4. Translator to MessageSelector: Translator creates/uses MessageSelector for pluralization src/Translator.php394-401
  5. Translator to Context: Translator stores locale in Hyperf Context for request isolation src/Translator.php432-446

For more details on these systems:

Sources: src/Functions.php1-47 src/Translator.php19-505