-
Notifications
You must be signed in to change notification settings - Fork 2
Translator
Pair\Helpers\Translator is Pair’s localization singleton.
It is responsible for:
- resolving the current locale
- loading module, application, and framework translation files
- returning translated strings with placeholder binding
- providing small helpers for option lists and object collections
Translator is used constantly by Controller, View, Application, and many UI helpers.
Returns the singleton translator.
Return the active locale and the default application locale.
On first use, the translator:
- loads the default locale from configuration/data
- uses that as the temporary current locale
- optionally inspects
HTTP_ACCEPT_LANGUAGE - switches to the browser-preferred locale if Pair can resolve it
Changes the active locale and reloads translation strings when needed.
Example:
use Pair\Helpers\Translator;
use Pair\Models\Locale;
$translator = Translator::getInstance();
// Loads one locale from your application data.
$locale = new Locale(2);
// Switches the current translator locale.
$translator->setLocale($locale);Resets the current locale back to the default one and reloads the strings cache.
Convenience helper that returns the current language code, for example it or en.
Defines the module namespace used for module-level translations.
Controllers do this automatically in their constructor, but it is useful in scripts, widgets, or custom rendering flows.
Example:
use Pair\Helpers\Translator;
$translator = Translator::getInstance();
// Forces module translation lookup under modules/orders/translations/.
$translator->setModuleName('orders');Current loading order is important because the first matching key wins:
APPLICATION_PATH/modules/<module>/translations/<current-locale>.iniAPPLICATION_PATH/translations/<current-locale>.ini- Pair framework
translations/<current-locale>.ini - the same three locations again for the default locale, when current and default locales differ
This means:
- module strings override app/framework strings
- current-locale strings override default-locale fallback strings
- already-loaded keys are not overwritten by later files
Translator::do(string $key, string|\Stringable|int|float|array|null $vars = null, bool $warning = true, string|Callable|null $default = null): string
This is the main method of the class and the one you will use most often.
Behavior:
- loads string files lazily
- looks up the key in the merged string set built from current-locale files first and default-locale files later
- if missing, optionally uses the provided
$default - logs warnings for missing or invalid translations when
$warningistrue - binds
%splaceholders throughvsprintf()
Example:
use Pair\Helpers\Translator;
// Reads one plain translation key.
$title = Translator::do('WELCOME_TITLE');
// Binds placeholder values into a string like "Welcome, John".
$message = Translator::do('WELCOME_USER', ['John']);
// Returns a custom fallback string without exposing [MISSING_KEY].
$fallback = Translator::do('MISSING_KEY', null, false, 'Default text');The current implementation behaves like this:
- if
$defaultis a string, that string is returned - if
$defaultis a callable, the callable result is returned - if the key exists in the merged translation set, it is returned immediately
- if
$warningistrueand the key is still missing, the result is[KEY] - if
$warningisfalse, the raw key is returned without brackets
The $vars argument accepts either one placeholder value or an array of values for multiple placeholders.
Supported single values are:
stringStringableintfloat
Pair normalizes single values to the array shape expected by vsprintf().
This means numeric values can be passed directly when a translation string contains %s placeholders.
use Pair\Helpers\Translator;
// Produces a string such as "ActiveRecord class errors: 3".
$message = Translator::do('ACTIVE_RECORD_CLASS_ERRORS', 3);
// Produces a string such as "Score: 2.5".
$score = Translator::do('SCORE_LABEL', 2.5);Use an array when the translation contains more than one placeholder:
use Pair\Helpers\Translator;
// Binds both placeholder values in order.
$summary = Translator::do('ORDER_SUMMARY', [$orderNumber, $total]);bool is intentionally not part of the accepted scalar contract.
Convert boolean state to an explicit label, number, or translation key before calling Translator::do().
Example with a callable fallback:
use Pair\Helpers\Translator;
// Builds a fallback dynamically when the translation key is missing.
$label = Translator::do(
'UNKNOWN_STATUS',
null,
false,
function (string $key): string {
// Converts the key into a readable label.
return ucwords(strtolower(str_replace('_', ' ', $key)));
}
);Translator::safeDo(string $key, string|\Stringable|int|float|array|null $vars = null, ?string $default = null): string
Returns a translated string through the normal translator when runtime locale loading is safe. In CLI tests and early bootstrap paths where the database-backed locale cannot be initialized, it formats the fallback string directly.
This method accepts the same placeholder value types as Translator::do().
Fallback formatting uses vsprintf() when possible and returns the unformatted fallback if the placeholder count is invalid.
use Pair\Helpers\Translator;
// Safe in CLI or early bootstrap paths before database configuration exists.
$message = Translator::safeDo('ACTIVE_RECORD_CLASS_ERRORS', 3, 'ActiveRecord class errors: %s');Returns whether the key exists in the loaded translation set available to the current translator state.
Translates select-option labels when the text is uppercase and longer than three characters. This is intentional: labels already written as normal human text are left untouched.
Example:
use Pair\Helpers\Translator;
$translator = Translator::getInstance();
$options = $translator->translateSelectOptions([
'paid' => 'PAID',
'draft' => 'Draft',
]);
// "PAID" is translated, "Draft" is left as-is.Adds a translated property named translated<PropertyName> to each item in the list.
Example:
use Pair\Helpers\Translator;
$translator = Translator::getInstance();
// Adds translatedStatus to each item when status exists.
$orders = $translator->translateActiveRecordList($orders, 'status');After this call, an item with property status will also expose translatedStatus.
Returns the default locale file name, for example it-IT.ini.
use Pair\Helpers\Translator;
$translator = Translator::getInstance();
// Forces module-specific strings first.
$translator->setModuleName('orders');
// Reads a label using module -> app -> framework fallback order.
$statusLabel = Translator::do('ORDER_STATUS_PAID');These methods are not called as often as do(), but they explain the translator lifecycle:
-
getCurrentLocale(): LocaleReturns the current locale after lazy initialization. -
getDefaultLocale(): LocaleReturns the application default locale. -
resetLocale(): voidClears the current string cache and reloads the default locale. -
getCurrentLanguageCode(): ?stringConvenient for templates, meta tags, and frontend bootstrapping.
-
Translatorapplies the active locale to PHP throughsetlocale(...). - Placeholder binding uses
vsprintf(), so translation strings should use%s-style placeholders. - Single string,
Stringable, integer, and float values are normalized before formatting. - Boolean placeholder state should be converted explicitly before translation.
- Invalid placeholder counts are logged as warnings instead of crashing the request.
- Controllers usually set the module automatically; in scripts or widgets you may need to call
setModuleName()yourself. - In the current implementation, default-locale files are merged into the main string set after current-locale files, so fallback keys are often returned silently once loaded.
See also: Controller, View, Application, Configuration-file.