Silex:使用闪存数据重定向


Silex: Redirect with Flash Data

我需要将一个页面重定向到另一个页面,并在 Silex 中显示一条消息。希望有一种Laravelesque的方式来做到这一点,但我非常怀疑它:

$app->redirect('/here', 301)->with('message', 'text');

然后,我想在我的模板中显示消息:

{{ message }}

如果没有,还有别的办法吗?

更新

我看到Symfony中有一个getFlashBag的方法 - 这是我应该使用的吗?具体来说,我使用的是 Bolt 内容管理系统。

是的,FlashBag 是正确的方法。在控制器中设置闪光消息(您可以添加多条消息):

$app['session']->getFlashBag()->add('message', 'text');
$app->redirect('/here', 301)

并在模板中打印:

{% for message in app.session.getFlashBag.get('message') %}
    {{ message }}
{% endfor %}

我创建了这个可能有用的简单FlashBagTrait

<?php
use Symfony'Component'HttpFoundation'Session'Flash'FlashBagInterface;
trait FlashBagTrait
{
    /**
     * @return FlashBagInterface
     */
    public function getFlashBag() {
        return $this['session']->getFlashBag();
    }
}

只需将其添加到您的Application类中,它就会让事情变得如此简单!

$app->getFlashBag()->add('message',array('type'=>"danger",'content'=>"You shouldn't be here"));
{% if app.flashbag.peek('message') %}
<div class="row">
    {% for flash in app.flashbag.get('message') %}
        <div class="bs-callout bs-callout-{{ flash.type }}">
            <p>{{ flash.content }}</p>
        </div>
    {% endfor %}
</div>
{% endif %}

它的主要优点是类型提示可以在PhpStorm中工作。

您也可以将其添加为服务提供商,

$app['flashbag'] = $app->share(function (Application $app) {
    return $app['session']->getFlashBag();
});

这使得从 PHP 使用更方便(但你失去了类型提示):

$app['flashbag']->add('message',array('type'=>"danger",'content'=>"You shouldn't be here"));