php-standard-library/locale
PHP Standard Library Locale component providing locale-aware formatting and parsing utilities. Helps handle language/region settings, localized dates, numbers, and other internationalization tasks in PHP apps with a lightweight, straightforward API.
Installation
composer require php-standard-library/locale
Add to composer.json under require if not auto-loaded.
First Use Case: Validating User Locale Input
use Locale\Locale;
$userLocale = 'en_US'; // From a form or request
$locale = Locale::fromString($userLocale);
if ($locale->isValid()) {
// Proceed with normalized locale
$normalized = $locale->toString(); // 'en_US'
$language = $locale->getLanguage(); // 'en'
} else {
// Fallback to default
$locale = Locale::fromString('en');
}
Where to Look First
Locale\Locale (main value object)Locale::isValid() or Locale::tryFromString()toString(), getLanguage(), getRegion()Locale\Locale PHPDoc for method signatures.Pattern: Sanitize locale input from requests (e.g., API, forms).
use Illuminate\Http\Request;
use Locale\Locale;
public function updateProfile(Request $request)
{
$locale = $request->input('locale');
$validatedLocale = Locale::tryFromString($locale) ?? Locale::fromString('en');
// Store normalized locale in user model
auth()->user()->update(['locale' => $validatedLocale->toString()]);
}
Pattern: Store and retrieve locales as typed objects.
use Locale\Locale;
class User extends Model
{
protected $casts = [
'locale' => Locale::class, // Automatically parses/validates
];
public function getDefaultLocaleAttribute()
{
return $this->locale->getLanguage(); // e.g., 'en'
}
}
Pattern: Extend Laravel’s trans() helper with locale-aware defaults.
use Illuminate\Support\Facades\App;
use Locale\Locale;
function transWithLocale(string $key, array $replace = [], string|null $locale = null): string
{
$appLocale = $locale ?? App::getLocale();
$normalizedLocale = Locale::fromString($appLocale)->toString();
return trans($key, $replace, [], $normalizedLocale);
}
Pattern: Chain fallbacks for missing locales.
use Locale\Locale;
function getFallbackLocale(string $preferred): Locale
{
return Locale::tryFromString($preferred)
?? Locale::fromString('en_GB')
?? Locale::fromString('en');
}
Pattern: Ensure consistent locale formatting in responses.
use Locale\Locale;
public function getUserLocales(User $user)
{
return [
'primary' => $user->locale->toString(), // 'en_US'
'language' => $user->locale->getLanguage(), // 'en'
'region' => $user->locale->getRegion(), // 'US'
];
}
Case Sensitivity
Locale::fromString('EN_US') may fail if the package enforces lowercase.$locale = Locale::fromString(strtolower($input));
Invalid Locale Handling
Locale::fromString('invalid') throws an exception by default.tryFromString() for silent fallback:
$locale = Locale::tryFromString($input) ?? Locale::fromString('en');
Region vs. Script Confusion
zh_Hans for Chinese Simplified).getScript() if working with complex locales.Laravel Cache Key Collisions
cache()->remember('translations_'.$locale, ...)) may clash if locales aren’t normalized.$locale->toString() as the cache key.Validate Locales Early: Add a middleware to validate request locales:
public function handle(Request $request, Closure $next)
{
if ($request->has('locale') && !Locale::tryFromString($request->locale)) {
abort(422, 'Invalid locale format.');
}
return $next($request);
}
Log Invalid Locales:
try {
$locale = Locale::fromString($input);
} catch (\InvalidArgumentException $e) {
\Log::warning("Invalid locale '$input'", ['exception' => $e]);
$locale = Locale::fromString('en');
}
Custom Validation Rules Extend Laravel’s validation with a custom rule:
use Illuminate\Validation\Rule;
use Locale\Locale;
Rule::macro('valid_locale', function ($field, $attribute, $parameters) {
return Rule::custom(function ($attribute, $value) use ($field) {
return Locale::tryFromString($value) !== null;
});
});
// Usage:
$request->validate(['locale' => 'valid_locale']);
Locale-Specific Logic
Use the Locale object to dispatch behavior:
$locale = Locale::fromString($user->locale);
if ($locale->getRegion() === 'US') {
// Apply US-specific formatting
}
Testing Mock locales in tests to avoid flakiness:
$this->app->singleton(Locale::class, function () {
return Locale::fromString('test_locale');
});
getLanguage()/getRegion() over toString() if you only need parts of the locale.config/app.php:
'locale' => Locale::fromString('en')->toString(),
How can I help you explore Laravel packages today?