lastdragon-ru/lara-asp-formatter
Installation:
composer require lastdragon-ru/lara-asp-formatter
Publish the config (if needed):
php artisan vendor:publish --provider="LastDragon\LaraAspFormatter\LaraAspFormatterServiceProvider" --tag="config"
First Use Case: Format a number or date using the built-in Intl wrappers:
use LastDragon\LaraAspFormatter\Facades\AspFormatter;
// Format a number (e.g., 1000 to "1,000")
$formattedNumber = AspFormatter::formatNumber(1000, 'en_US');
// Format a date (e.g., timestamp to "MM/dd/yyyy")
$formattedDate = AspFormatter::formatDate(now(), 'MM/dd/yyyy', 'en_US');
Check the Config:
Review config/lara-asp-formatter.php for default locales, formats, and customizations.
Locale-Aware Formatting: Use the facade or service container to dynamically format values based on user locale:
$locale = app()->getLocale(); // e.g., 'fr_FR'
$formattedPrice = AspFormatter::formatNumber(1234.56, 'currency', $locale);
Custom Format Definitions:
Define reusable formats in config/lara-asp-formatter.php:
'custom_formats' => [
'short_date' => 'MMM d, yyyy', // e.g., "Jan 1, 2023"
'file_size' => '::.2f B', // e.g., "1.23 KB"
],
Use them in code:
$formattedDate = AspFormatter::formatDate(now(), 'short_date');
Integration with Laravel Views: Inject the formatter into Blade templates via a helper or service:
// In a controller
return view('dashboard', ['formatter' => AspFormatter::class]);
<!-- In Blade -->
{{ $formatter::formatNumber($value, 'en_US') }}
Request-Based Formatting: Attach formatting logic to incoming requests (e.g., API responses):
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource {
public function toArray($request) {
return [
'name' => $this->name,
'created_at' => AspFormatter::formatDate($this->created_at, 'short_date', $request->locale),
];
}
}
Validation Feedback: Use the formatter to display user-friendly validation messages:
$validator = Validator::make($data, [
'price' => 'required|numeric',
], [
'price.numeric' => 'Please enter a valid number (e.g., ' . AspFormatter::formatNumber(1000, 'en_US') . ').',
]);
Dynamic Locale Switching: Override the default locale per request or context:
$formattedValue = AspFormatter::setLocale('de_DE')->formatNumber(1000);
Chaining Formatters: Combine multiple formats in a single pass:
$formatted = AspFormatter::formatNumber($value, 'currency', 'en_US')
->formatDate($date, 'short_date', 'fr_FR');
Testing: Mock the formatter in tests to isolate logic:
$this->app->instance(\LastDragon\LaraAspFormatter\Contracts\AspFormatter::class, MockFormatter::class);
Service Container Binding: Bind custom formatters to the container for dependency injection:
$this->app->bind('custom.formatter', function () {
return new CustomFormatter(AspFormatter::class);
});
Locale Fallbacks:
en_US if the requested locale is unsupported. Explicitly handle fallbacks:
$locale = $request->locale ?? 'en_US';
$formatted = AspFormatter::formatNumber(1000, 'currency', $locale);
Intl Extension Requirements:
intl PHP extension is enabled. Test with:
php -m | grep intl
pecl install intl
or enable in php.ini:
extension=intl
Caching Static Formats:
$cacheKey = "formatted_{$value}_{$format}_{$locale}";
$formatted = cache()->remember($cacheKey, now()->addHours(1), function () use ($value, $format, $locale) {
return AspFormatter::formatNumber($value, $format, $locale);
});
Date/Time Zone Sensitivity:
date_default_timezone_set('UTC');
$formatted = AspFormatter::formatDate(now(), 'yyyy-MM-dd');
Custom Format Syntax:
IntlDateFormatter/NumberFormatter syntax. Test edge cases:
// May fail if locale doesn't support the pattern
AspFormatter::formatDate(now(), 'E, MMM d, yyyy', 'ja_JP');
Validate Locale Support: Check supported locales with:
$supportedLocales = AspFormatter::getSupportedLocales();
Log Format Errors: Wrap formatting in a try-catch to log unsupported patterns:
try {
$formatted = AspFormatter::formatDate($date, $pattern, $locale);
} catch (\IntlException $e) {
Log::error("Format failed: {$pattern} for locale {$locale}", ['exception' => $e]);
$formatted = $date; // Fallback
}
Inspect Raw Intl Objects:
Access underlying NumberFormatter/DateFormatter for debugging:
$formatter = AspFormatter::getNumberFormatter('en_US', \NumberFormatter::CURRENCY);
var_dump($formatter->getPattern());
Custom Formatters: Extend the base formatter for domain-specific logic:
class AppFormatter extends \LastDragon\LaraAspFormatter\AspFormatter {
public function formatFileSize(int $bytes, string $locale = 'en_US'): string {
$units = ['B', 'KB', 'MB', 'GB'];
$unit = 0;
while ($bytes > 1024 && $unit < count($units) - 1) {
$bytes /= 1024;
$unit++;
}
return $this->formatNumber($bytes, '::.2f', $locale) . ' ' . $units[$unit];
}
}
Service Provider Hooks: Override defaults in the service provider:
public function register() {
$this->app->singleton(\LastDragon\LaraAspFormatter\Contracts\AspFormatter::class, function () {
return new AppFormatter(config('lara-asp-formatter'));
});
}
Artisan Commands: Add commands to validate or generate formats:
Artisan::command('formatter:test', function () {
$this->info(AspFormatter::formatDate(now(), 'yyyy-MM-dd', 'en_US'));
});
How can I help you explore Laravel packages today?