【问题标题】:Silex: Redirect with Flash DataSilex:使用 Flash 数据重定向
【发布时间】:2013-10-06 12:09:58
【问题描述】:

我需要使用 Silex 中的消息将一个页面重定向到另一个页面。希望有一种 Laravelesque 的做法,但我非常怀疑:

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

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

{{ message }}

如果没有,还有其他方法吗?

更新

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

【问题讨论】:

    标签: php redirect http-status-code-301 silex


    【解决方案1】:

    我创建了这个可能有用的简单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"));
    

    【讨论】:

      【解决方案2】:

      是的,FlashBag 是正确的方法。 在你的控制器中设置一个 flash 消息(你可以添加多个消息):

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

      并在模板中打印出来:

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

      【讨论】:

      • 要扩展@a4c8b 答案,请注意这将为每个请求创建一个会话cookie。修复请加peekAll,见Nyholm's gist
      猜你喜欢
      • 2016-08-23
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 2015-12-28
      • 1970-01-01
      • 2017-10-01
      相关资源
      最近更新 更多