Skip to content

michael-rubel/laravel-formatters

Repository files navigation

Laravel Formatters

Laravel Formatters

Latest Version on Packagist Total Downloads Code Quality Code Coverage GitHub Tests Action Status PHPStan

This package introduces the Formatter pattern you can use to standardize data formats in your Laravel application. You can write your own formatters and put them in app/Formatters folder, then apply them everywhere in your application through format helper. The package uses the Service Container under the hood to easily extend or override the formatter classes.


The package requires PHP 8.1 or higher and Laravel 10 or higher. If you're looking for older versions, check release history.

#StandWithUkraine

SWUbanner

Installation

Install the package via composer:

composer require michael-rubel/laravel-formatters
php artisan vendor:publish --tag="formatters-config"

Usage

format(DateTimeFormatter::class, now());

You can use a shorter version of the string as an alternative:

format('date-time', now());

Available built-in formatters

Artisan command

To make the programmer's life easier, we also added the Artisan command. You can use make:formatter command to generate formatter classes. It will put the class with the given name into app/Formatters folder and auto-inject the stub.

Extending formatters

Since the formatters are resolved through the Service Container they can be easily overridden by extending bindings.

For example in your Service Provider:

$this->app->extend(DateTimeFormatter::class, function ($formatter) {
    $formatter->datetime_format = 'Y.m.d H:i';

    return $formatter;
});

Adding custom/overriding package formatters

To add a custom formatter you should create the class that implements the MichaelRubel\Formatters\Formatter interface and put it to the app/Formatters folder. You can put formatter with the same name as the package's to override the formatter from the package. You can customize the folder in the config file.

Examples

You can discover examples of the usage here.

Contributing

If you have written your own formatter and want to add it to this package, PRs are welcomed. But take care of the extendability of the formatter you want to make as built-in and remember to write tests for your use cases.

Testing

composer test