🇵🇸 Solidarity with Palestine. We seek justice and peace, and strongly oppose all forms of injustice and genocide.

If you find PHPFlasher useful, please consider giving it a ⭐ star on GitHub 😊. If you spot any typos or have suggestions, feel free to contribute to the documentation 📝. Your feedback helps keep the project up-to-date and well-maintained. Thank you


Requirements

PHPFlasher helps you easily add flash notifications to your Symfony projects, improving user feedback with minimal setup.

To use PHPFlasher with Symfony, you need:

PHP v8.2 or higher Symfony v7.0 or higher


Installation

PHPFlasher is modular. You can install only the parts you need.

Run this command to install it:

composer require php-flasher/flasher-symfony

After installing, run this command to set up the required assets:

php bin/console flasher:install

Usage

To show a notification message, you can use the flash() helper function or get an instance of flasher from the service container. Before you return a view or redirect, call one of the notification methods like success() and pass in the message you want to display.

#/ PHPFlasher

use Flasher\Prime\FlasherInterface;

class BookController
{
    public function saveBook()
    {
        // ...

        flash()->success('Your donation has been received.');

        flash('Your account has been restored.');

        // ... redirect or render a view
    }
    
    /**
     * if you prefer to use dependency injection 
     */
    public function register(FlasherInterface $flasher)
    {
        // ...

        $flasher->success('Your account has been deactivated.');

        // ... redirect or render a view
    }
}


Choose a message that is clear and tells the user what happened. For example, "Book has been created successfully!" is a good message, but you can adjust it to fit your application’s context and language.

Using this package is easy. You can add notifications to your application with just one line of code.

#/ usage success

flash()->success('Your order has been placed.');
#/ usage error

flash()->error('Sorry, something went wrong.');
#/ usage warning

flash()->warning('Your account may not have been locked.');
#/ usage info

flash()->info('Your account has been linked and a confirmation email has been sent.');

These four methods — success(), error(), warning(), and info() — are shortcuts for the flash() method. They let you specify the type and message in one method call instead of passing them separately to flash().

flash()->flash(string $type, string $message, array $options = [], string $title = null)
#/ usage flash

flash()->flash('success', 'Your payment was processed successfully.');
Parameter Description
$type Notification type: success, error, warning, info
$message The message you want to show to the user. This can include HTML. If you add links, make sure to add the right classes for your framework.
$title The notification title. Can also include HTML.
$options Custom options for JavaScript libraries (toastr, noty, notyf, etc.).

options

The options() method lets you set multiple options at once by passing an array of key-value pairs. The option() method lets you set a single option by specifying its name and value. The $append argument for options() decides whether the new options should be added to existing ones (true) or replace them (false).

flash()->options(array $options, bool $append = true);
#/ usage options

flash()
    ->options([
        'timeout' => 3000, // 3 seconds
        'position' => 'top-center',
    ])
    ->warning('Warning: This cannot be undone.');

option

To set a single option:

flash()->option(string $option, mixed $value);
#/ usage option

flash()
    ->option('position', 'bottom-right')
    ->option('timeout', 3000)
    ->error('There was a problem restoring your account.');

priority

Set the priority of a flash message. Messages with higher priority appear first.

flash()->priority(int $priority);
#/ usage priority

flash()
    ->priority(3)
    ->success('Priority 3 → Your account has been restored.');

flash()
    ->priority(1)
    ->error('Priority 1 → Something went wrong.');

flash()
    ->priority(4)
    ->warning('Priority 4 → Your account may not have been re-verified.');

flash()
    ->priority(2)
    ->info('Priority 2 → Your report has been generated and a confirmation email has been sent.');
param description
$priority The priority of the notification. Higher numbers are shown first.

hops

The hops() method sets how many requests the flash message should last for. By default, flash messages show for one request. Setting the number of hops makes the message stay for multiple requests.

For example, in a multi-page form, you might want to keep messages until all pages are completed.

flash()->hops(int $hops);
flash()
    ->hops(2)
    ->info('Your account has been verified and is now active.');
param description
$hops Number of requests the flash message will persist for

translate

The translate() method sets the locale for translating the flash message. If you provide a locale, the message will be translated to that language. If you pass null, it uses the default locale.

flash()->translate(string $locale = null);
#/ usage translate

flash()
    ->translate('ar')
    ->success('Your request was processed successfully.', 'Congratulations!');
#/ usage translate with position

flash()
    ->translate('ar')
    ->option('position', 'top-left')
    ->success('Your request was processed successfully.', 'Congratulations!');
param description
$locale The locale to use for translation, or null for the default

Note: The translate() method only sets the locale. It doesn’t translate the message by itself.

To translate the message, you need to add the translation keys in your translation files.

For example, to translate the message into Arabic, add these keys to translations/messages.ar.yaml:

Your request was processed successfully.: 'تمت العملية بنجاح.'
Congratulations!: 'تهانينا'

Configuration

If you want to change the default settings, you can publish the configuration file:

php bin/console flasher:install --config

This will create a file at config/packages/flasher.yaml with the following content:

# config/packages/flasher.yaml

flasher:
    # Default notification library (e.g., 'flasher', 'toastr', 'noty', 'notyf', 'sweetalert')
    default: flasher

    # Path to the main PHPFlasher JavaScript file
    main_script: '/vendor/flasher/flasher.min.js'

    # List of CSS files to style your notifications
    styles:
        - '/vendor/flasher/flasher.min.css'

    # Set global options for all notifications (optional)
    # options:
    #     # Time in milliseconds before the notification disappears
    #     timeout: 5000
    #     # Where the notification appears on the screen
    #     position: 'top-right'
  
    # Automatically inject JavaScript and CSS assets into your HTML pages
    inject_assets: true

    # Enable message translation using Symfony's translation service
    translate: true

    # URL patterns to exclude from asset injection and flash_bag conversion
    excluded_paths:
        - '/^\/_profiler/'
        - '/^\/_fragment/'

    # Map Symfony flash message keys to notification types
    flash_bag:
      success: ['success']
      error: ['error', 'danger']
      warning: ['warning', 'alarm']
      info: ['info', 'notice', 'alert']
  
    # Set criteria to filter which notifications are displayed (optional)
    # filter:
    #     # Maximum number of notifications to show at once
    #     limit: 5

    # Define notification presets to simplify notification creation (optional)
    # presets:
    #     # Example preset:
    #     entity_saved:
    #         type: 'success'
    #         title: 'Entity saved'
    #         message: 'Entity saved successfully'


Presets

You can create a preset for a custom notification that you want to reuse in multiple places. Add a presets entry in the configuration file.

A preset is like a pre-defined message you can use in many places.

For example, create a preset named entity_saved:

# config/packages/flasher.yaml

flasher:
    presets:
        entity_saved:
            type: 'success'
            message: 'Entity saved successfully'
            title: 'Entity saved'

To use the preset, call the preset() method and pass the name of the preset:

#/ symfony preset

class BookController
{
    public function save()
    {
        flash()->preset('entity_saved');

This is the same as:

class BookController
{
    public function save()
    {
        flash()->success('Entity saved successfully', 'Entity saved');

Variables

Presets can also have variables that you can replace using the translation system. For example, you can have a preset that shows a personalized welcome message.

# config/packages/flasher.yaml

flasher:
    presets:
        hello_user:
            type: success
            message: welcome_back_user

In your translation file, define welcome_back_user with a message containing the variable :username.

# translations/flasher.en.yaml

welcome_back_user: Welcome back :username

To replace :username with the actual username in your controller, pass an array with the values to substitute as the second argument:

class BookController
{
    public function save()
    {
        $username = 'John Doe';

        flash()->preset('hello_user', ['username' => $username]);


RTL support

PHPFlasher makes it easy to use right-to-left languages like Arabic or Hebrew. It automatically detects the text direction and adjusts accordingly.

Just make sure the translation service is enabled, and PHPFlasher will handle the rest.

#/ phpflasher rtl

flash()
    ->translate('ar')
    ->success('Your request was processed successfully.', 'Congratulations!');

Translation

PHPFlasher lets you translate your notification messages and presets. It comes with translations for Arabic, English, French, German, Spanish, Portuguese, Russian, and Chinese. You can also add your own translations.

To override the English translations for PHPFlasher, create a file at translations/flasher.en.yaml.

In this file, define only the translation strings you want to change. Any strings you don’t override will use PHPFlasher’s default translations.

Here are examples of the default translation keys for Arabic, English, and French:

# translations/flasher.ar.yaml

success: 'نجاح'
error: 'خطأ'
warning: 'تحذير'
info: 'معلومة'

The resource was created: 'تم إنشاء :resource'
The resource was updated: 'تم تعديل :resource'
The resource was saved: 'تم حفظ :resource'
The resource was deleted: 'تم حذف :resource'

resource: 'الملف'
# translations/flasher.en.yaml

success: 'Success'
error: 'Error'
warning: 'Warning'
info: 'Info'

The resource was created: 'The :resource was created'
The resource was updated: 'The :resource was updated'
The resource was saved: 'The :resource was saved'
The resource was deleted: 'The :resource was deleted'

resource: 'resource'
# translations/flasher.fr.yaml

success: 'Succès'
error: 'Erreur'
warning: 'Avertissement'
info: 'Information'

The resource was created: 'La ressource :resource a été ajoutée'
The resource was updated: 'La ressource :resource a été mise à jour'
The resource was saved: 'La ressource :resource a été enregistrée'
The resource was deleted: 'La ressource :resource a été supprimée'

resource: ''

These translation files help you localize notifications to match user preferences, so your application can communicate effectively in different languages.

#/ symfony arabic translations

// Translate the flash message using the PHPFlasher translation files
flash()->success('The resource was created');

flash()->error('حدث خطأ أثناء إرسال طلبك.');
flash()->warning('يجب إكمال جميع الحقول الإلزامية قبل إرسال النموذج');
flash()->info('سيتم تحديث هذه الصفحة في غضون 10 دقائق.');
#/ symfony french translations

// Translate the flash message using the PHPFlasher translation files
flash()->success('The resource was created');

flash()->error('Une erreur s’est produite lors de l’envoi de votre demande.');
flash()->warning('Vous devez remplir tous les champs obligatoires avant de soumettre le formulaire.');
flash()->info('Cette page sera mise à jour dans 10 minutes.');
Younes

PHPFlasher is a project by Younes ENNAJI.