概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:39:53 | 115 次阅读 | 评论: 0 | 来源: 网络整理

Sessions are automatically started whenever you read, write or even check for the existence of data in the session. This means that if you need to avoid creating a session cookie for some users, it can be difficult: you must completely avoid accessing the session.

For example, one common problem in this situation involves checking for flash messages, which are stored in the session. The following code would guarantee that a session is always started:

{% for flashMessage in app.session.flashbag.get('notice') %}
    <div class="flash-notice">
        {{ flashMessage }}
    </div>
{% endfor %}

Even if the user is not logged in and even if you haven’t created any flash messages, just calling the get() (or even has()) method of the flashbag will start a session. This may hurt your application performance because all users will receive a session cookie. To avoid this behavior, add a check before trying to access the flash messages:

{% if app.request.hasPreviousSession %}
    {% for flashMessage in app.session.flashbag.get('notice') %}
        <div class="flash-notice">
            {{ flashMessage }}
        </div>
    {% endfor %}
{% endif %}
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务