Flash Messages
The Flash Messages middleware in Lithe allows you to store and retrieve temporary messages between requests.
Using the Flash Messages Middleware
The Flash Messages middleware in Lithe allows you to store temporary messages in the session, which can be accessed on the next request. This is useful for displaying status messages, such as confirmations or errors, after an operation.
Configuring the Flash Middleware
To use the Flash Messages middleware, you need to add it to your application using the use()
method:
use Lithe\Middleware\Session\flash;
$app->use(flash());
This adds the flash message functionality to your application, allowing you to store and retrieve temporary messages.
Setting Flash Messages
To set a flash message, you can use the magic __set
method or the set
method of the Flash
class. Both approaches store the message in the session so that it is available on the next request.
-
Using the magic
__set
method:$req->flash->successMessage = 'Operation completed successfully!';
-
Using the
set
method:$req->flash->set('successMessage', 'Operation completed successfully!');
Retrieving Flash Messages
To retrieve and remove a flash message from the session, you can use the magic __get
method or the get
method of the Flash
class. These messages are removed from the session after they are retrieved.
-
Using the magic
__get
method:$message = $req->flash->successMessage;
-
Using the
get
method:$message = $req->flash->get('successMessage');
Checking Flash Messages
To check if one or more flash messages exist in the session, use the has
method:
-
Single Check:
$exists = $req->flash->has('successMessage');
-
Multiple Checks:
$exists = $req->flash->has(['successMessage', 'errorMessage']);
Keeping Flash Messages
If you want to keep a flash message for the next request (i.e., make it available in more than one request), use the keep
method:
$req->flash->keep('successMessage');
This reconfigures the message for the next request after retrieval.
Considerations
- Persistence: Flash messages are removed from the session after the first retrieval unless you use the
keep
method to preserve them. - Security: Ensure that retrieved messages are sanitized to avoid security issues like XSS attacks.