Эта библиотека позволяет вам использовать временные сообщения в вашем тонком проекте. Он легко интегрируется с системой шаблонов ветки посредством расширения, которое обеспечивает функции для захвата и использования в шаблоне. Он не ограничивается созданием простых строк сообщений, но также позволяет использовать другие типы данных, такие как массивы.
composer require williamsampaio/slim-flash-messages // app/dependencies.php
//...
use SlimFlashMessages Flash ;
use SlimFlashMessages FlashProviderInterface ;
return function ( ContainerBuilder $ containerBuilder ) {
$ containerBuilder -> addDefinitions ([
//...
FlashProviderInterface::class => function () {
return Flash:: getInstance ();
},
]);
}; // app/middleware.php
//...
// use SlimFlashMessagesFlashMiddleware;
use SlimFlashMessages FlashTwigExtension ;
return function ( App $ app ) {
//...
// Optional if you are working with dependency injection,
// using the middleware is only useful if you need to obtain the Flash instance from request.
// $app->add(FlashMiddleware::createFromContainer($app));
// With Twig
$ twig = Twig:: create ( __DIR__ . ' /../templates ' , [ ' cache ' => false ]);
$ twig -> addExtension (FlashTwigExtension:: createFromContainer ( $ app ));
$ app -> add (TwigMiddleware:: create ( $ app , $ twig ));
}; // Your controller
//...
use Slim Views Twig ;
// use SlimFlashMessagesFlashProvider;
use SlimFlashMessages FlashProviderInterface ;
class YourController
{
private $ flash ;
private $ view ;
public function __construct ( FlashProviderInterface $ flash , Twig $ view )
{
$ this -> flash = $ flash ;
$ this -> view = $ view ;
}
public function index ( ServerRequestInterface $ request , ResponseInterface $ response )
{
// If you are working with middleware instead of dependency injection it will be this way.
// $flash = FlashProvider::fromRequest($request);
$ this -> flash -> add ( ' messages ' , ' Hello! ' );
return $ this -> view -> render ( $ response , ' template.twig ' );
}
//...
} {# template.twig #}
{% for msg in flash( ' messages ' ) %}
{{ msg }}
{% endfor %}Интеграция Twig не является обязательной, как вы можете видеть в этом примере, где основное внимание уделяется демонстрации API поставщика сообщений.
<?php
use Psr Http Message ResponseInterface as Response ;
use Psr Http Message ServerRequestInterface as Request ;
use Slim Factory AppFactory ;
use SlimFlashMessages Flash ;
use SlimFlashMessages FlashMiddleware ;
use SlimFlashMessages FlashProvider ;
require __DIR__ . ' /../vendor/autoload.php ' ;
// Important! if the storage is not passed to the constructor,
// $_SESSION will be used
$ flash = Flash:: getInstance ();
// Create App
$ app = AppFactory:: create ();
$ app -> setBasePath ( ' /example1 ' ); // Optional
// Add FlashMiddleware
$ app -> add ( new FlashMiddleware ( $ flash ));
$ app -> addErrorMiddleware ( true , true , true );
$ app -> get ( ' / ' , function ( Request $ request , Response $ response , $ args ) {
// Get FlashProvider from request
// FlashMiddleware previously took care of adding the FlashProvider to the request
$ flash = FlashProvider:: fromRequest ( $ request );
// Clear all stored values
$ flash -> clearAll ();
// The 'add' method allows you to add a flash message or data (as an array, if you prefer!)
$ flash -> add ( ' simple ' , ' Hello World! 1 ' );
$ flash -> add ( ' messages ' , [
' status ' => ' success ' ,
' text ' => ' 1. PHP is the best! '
]);
echo ' <pre> ' ;
var_dump ( $ flash -> getAll ());
// Checks if the key is defined in the storage
var_dump ( $ flash -> has ( ' messages ' ));
// Clear a key defined
$ flash -> clear ( ' messages ' );
var_dump ( $ flash -> getAll ());
var_dump ( $ flash -> has ( ' messages ' ));
$ flash -> add ( ' simple ' , ' Hello World! 2 ' );
$ flash -> add ( ' simple ' , ' Hello World! 3 ' );
var_dump ( $ flash -> getAll ());
// Get first item from key
var_dump ( $ flash -> get_first ( ' simple ' ));
// or to pick up and remove first item.
// var_dump($flash->get_first('simple', true));
// Get last item from key
// var_dump($flash->get_last('simple'));
// or to pick up and remove last item.
var_dump ( $ flash -> get_last ( ' simple ' , true ));
var_dump ( $ flash -> get ( ' simple ' ));
return $ response ;
});
$ app -> run ();В этом примере используется контейнер PHP-DI и Slim/Twig-View.
<?php
use DI Container ;
use Psr Http Message ResponseInterface as Response ;
use Psr Http Message ServerRequestInterface as Request ;
use Slim Factory AppFactory ;
use Slim Views Twig ;
use Slim Views TwigMiddleware ;
use SlimFlashMessages Flash ;
use SlimFlashMessages FlashMiddleware ;
use SlimFlashMessages FlashProvider ;
use SlimFlashMessages FlashProviderInterface ;
use SlimFlashMessages FlashTwigExtension ;
require __DIR__ . ' /../vendor/autoload.php ' ;
// Create a new DI Container
$ container = new Container ();
// Add a FlashProvider to the container
$ container -> set (FlashProviderInterface::class, function () {
// Important! if the storage is not passed to the constructor,
// $_SESSION will be used
return Flash:: getInstance ();
});
// Set container to create App with on AppFactory
AppFactory:: setContainer ( $ container );
$ app = AppFactory:: create ();
$ app -> setBasePath ( ' /example2 ' ); // Optional
// Add FlashMiddleware from container
$ app -> add (FlashMiddleware:: createFromContainer ( $ app ));
// Create Twig and add FlashTwigExtension
$ twig = Twig:: create ( __DIR__ . ' /templates ' , [ ' cache ' => false ]);
$ twig -> addExtension (FlashTwigExtension:: createFromContainer ( $ app ));
// Add Twig-View Middleware
$ app -> add (TwigMiddleware:: create ( $ app , $ twig ));
$ app -> addErrorMiddleware ( true , true , true );
$ app -> get ( ' / ' , function ( Request $ request , Response $ response , $ args ) {
// Get Twig and FlashProvider from request
$ view = Twig:: fromRequest ( $ request );
// FlashMiddleware previously took care of adding the FlashProvider to the request
$ flash = FlashProvider:: fromRequest ( $ request , ' flash ' );
$ alerts = [ ' primary ' , ' secondary ' , ' success ' , ' danger ' , ' warning ' , ' info ' , ' light ' , ' dark ' ];
// The 'add' method allows you to add a flash message or data (as an array, if you prefer!)
$ flash -> add ( ' simple ' , ' Hello World! ' );
$ flash -> add ( ' messages ' , [
' alert ' => $ alerts [ array_rand ( $ alerts )],
' text ' => ' 1. PHP is the best! '
]);
$ flash -> add ( ' messages ' , [
' alert ' => $ alerts [ array_rand ( $ alerts )],
' text ' => ' 2. Slim Framework is amazing! '
]);
$ flash -> add ( ' messages ' , [
' alert ' => $ alerts [ array_rand ( $ alerts )],
' text ' => ' 3. Lorem ipsum! '
]);
return $ view -> render ( $ response , ' template.html.twig ' , [
' page ' => ' Slim Flash Messages ' ,
]);
});
$ app -> run ();В шаблоне:
{% for msg in flash( ' messages ' ) %}
< div class = " alert alert-{{ msg . alert }} alert-dismissible fade show " role = " alert " >
{{ msg . text }}
< button type = " button " class = " btn-close " data-bs-dismiss = " alert " aria-label = " Close " ></ button >
</ div >
{% endfor %}Самый простой способ запустить эти примеры - через Docker.
git clone https://github.com/WilliamSampaio/Slim-Flash-Messages.git
cd Slim-Flash-Messages
docker compose up -d --buildКогда вы завершите процесс UP, доступ:
FlashTwigExtension обеспечивает эти функции для ваших шаблонов ветки.
Он получает два дополнительных параметра: key (string/null = null ) и clear (bool = true ) .
key : если не указан, будет возвращен массив со всеми данными в хранилище, в противном случае будет возвращен только массив с данными, индексируемые значением ключа.clear : если неверно, элементы не будут удалены из хранилища после вызова функции. {% for msg in flash( ' messages ' , false ) %}
< div class = " alert alert-{{ msg . alert }} alert-dismissible fade show " role = " alert " >
{{ msg . text }}
< button type = " button " class = " btn-close " data-bs-dismiss = " alert " aria-label = " Close " ></ button >
</ div >
{% endfor %} Он получает два параметра: key (строка) и remove (bool = true ) .
key : Первый элемент из массива с данными, индексированными по значению ключа, будет возвращен.remove (необязательно): если неверно, элемент не будет удален из хранилища после вызова функции. {% set first = flash_first( ' messages ' ) %}
< div class = " alert alert-{{ first . alert }} alert-dismissible fade show " role = " alert " >
{{ first . text }}
< button type = " button " class = " btn-close " data-bs-dismiss = " alert " aria-label = " Close " ></ button >
</ div > Он получает два параметра: key (строка) и remove (bool = true ) .
key : Последний элемент из массива с данными, индексированными значением ключа, будет возвращен.remove (необязательно): если неверно, элемент не будет удален из хранилища после вызова функции. {% set last = flash_last( ' messages ' ) %}
< div class = " alert alert-{{ last . alert }} alert-dismissible fade show " role = " alert " >
{{ last . text }}
< button type = " button " class = " btn-close " data-bs-dismiss = " alert " aria-label = " Close " ></ button >
</ div > Он получает один параметры, key (строка) . Проверяет, определяется ли ключ в хранилище. Вернуть true или false .
key : ключ, который будет проверен. {{ flash_has( ' messages ' ) ? ' exists! ' : " it doesn't exist... " }} Он получает один дополнительные параметры, key (строка) . Удаляет данные из хранилища. Вернуть void .
key (необязательно): ключ, который будет удален. Если не определено, он удаляет все данные из хранилища. {{ flash_clear( ' messages ' ) }}Чтобы выполнить тестовый набор, вам нужно будет клонировать репозиторий и установить зависимости.
git clone https://github.com/WilliamSampaio/Slim-Flash-Messages.git
cd Slim-Flash-Messages
composer install
composer test
# Or
# composer coverage Лицензия MIT (MIT). Пожалуйста, смотрите файл лицензии для получения дополнительной информации.