hampel/alerts

Laravel 包,用于管理视图响应中的会话消息和警报

2.4.0 2023-06-02 06:39 UTC

README

Latest Version on Packagist Total Downloads Open Issues License

此包为 Laravel 提供会话驱动的警报,并为基于 Bootstrap 和 Foundation 的前端框架提供警报模板。

作者 Simon Hampel

安装

要通过 composer 安装,请运行以下命令

composer require hampel/alerts

如果您想更改默认的 Alert 配置或视图,首先使用以下命令发布它们

$ php artisan vendor:publish --provider="Hampel\Alerts\AlertServiceProvider"

配置文件可以在 config/alerts.php 中找到,视图在 resources/views/vendor/alerts

用法

警报功能基于两个类 - 第一个是 AlertManager 类,您可以通过 Alert 门面(或通过容器 $app['alerts'])在您的代码中访问它。AlertManager 类使用 Laravel MessageBag 来存储警报集合,警报按警报键(警告、错误、成功等)分组。

添加完警报后,您可以将它们“闪现”到会话中,以便在页面重定向后可以使用警报消息。

此时,功能的第一部分开始发挥作用。该包提供了一个视图组合器,它等待特定的视图被渲染,然后执行,注入从会话中检索的存储的警报信息。警报本质上是作为一系列子视图渲染的,这些子视图使用可配置的变量插入到基本视图中。

我们可以通过内置功能轻松地将警报添加到 AlertManager

Alert::add('error', 'An error message');

默认提供了四个警报级别:infowarningerrorsuccess。请注意,传递给 add 函数的任何不在配置的警报级别列表中的警报级别,在渲染视图时将被忽略。

您可以使用与配置的警报级别对应的简写函数将消息添加到 AlertManager

Alert::error('An error message');
Alert::success('Operation succeeded');

如果您希望使用消息的语言翻译文件,只需指定一个翻译键,AlertManager 就会替换相应的语言条目,并可选择应用任何替换。请注意,这仅在您使用简写函数添加消息时才有效。

Alert::success('auth.login.success');
Alert::error('validation.accepted', array('attribute' => 'terms'));

或者,您可以自己应用翻译

Alert::add('success', Lang::get('auth.login.success'));
Alert::error(Lang::get('validation.accepted', array('attribute' => 'terms')));

您可以获取底层 MessageBag 实现并将其合并到一个现有的 MessageBag。

$mybag = new MesageBag();
// add messages to your messagebag

// now get the alert message bag
$alerts = Alert::getMessageBag();

// merge in our messages
$alerts->merge($mybag);

// flash the messages to the session
Alert::flash();

要将警报消息传递到视图响应中,您需要将数据闪现到会话中。

您可以通过多种方式这样做 - AlertManager 类提供了一个 flash 函数,它会自动设置会话键,或者您可以在重定向响应的范围内这样做。如果不使用内置的 flash 函数,请确保您指定了配置文件中使用的会话键的名称 'alerts::session_key',或者使用辅助函数 Alerts::getSessionKey()

// flash the messages to the session - this is the easiest way to do it
Alert::success('Operation succeeded')->flash();

// alternatively, return a redirect response and let Laravel flash the messages
return Redirect::to('myroute')->with(Alert::getSessionKey(), Alert::error('There was a problem')->getMessageBag()->getMessages());

// you can always just do it all manually and not use the AlertManager at all!
$messages = new MessageBag;
$messages->add('info', Lang::get('something.happened.info'));
Session::flash(Config::get('alerts::session_key', $messages->getMessages());

该包提供了一个视图组合器,它会在调用视图时自动渲染警报。有几种方法可以做到这一点。

默认情况下,有一个 Blade 模板 alerts.blade.php,您可以将它包含到您的基视图中。视图组合器默认配置为监视此视图,并在渲染此视图时渲染警报。要使用,只需在视图中 @include 该模板即可

@include('alerts::alerts')

如果您希望自行操作,可以更改视图构建器的配置以监视不同的视图,甚至可能是您的 layouts.base 视图。构建器将生成警报数据并将其绑定到配置的变量名,然后您只需在视图中简单地输出它。

为Bootstrap和Foundation都提供了模板,尽管Foundation是默认的 - 如果您使用Bootstrap,则需要更改配置设置。或者,您也可以提供自己的视图模板来渲染每个警报消息。有关设置功能的更多信息,请参考配置文件。