【问题标题】:Symfony2 common session strategySymfony2 常用会话策略
【发布时间】:2013-04-19 15:36:59
【问题描述】:

我有一个 symfony2 网络项目,它由十个页面组成,通过 5 个控制器呈现。用户可以通过上述任何页面(例如通过共享链接)登陆网站。我需要向在当前会话期间首次打开页面的用户显示一个欢迎弹出窗口(只是带有position:absolute 的 div)。

我已经将弹出窗口放置在所有需要的页面都使用的通用树枝模板中。现在我必须确定是否显示弹出窗口。我将根据控制器的布尔值显示弹出窗口。

我必须使用会话和 cookie,但我必须在每个页面上都这样做,并且我不想在每个方法中编写相同的代码(检查和设置 cookie,输出一个布尔值以在模板中显示弹出窗口)每个控制器的。根据 DRY 概念,有没有办法做到这一点?

【问题讨论】:

    标签: symfony cookies dry


    【解决方案1】:

    您可以创建一个包装类来处理检查、设置和获取当前会话值并将其作为服务。

    <?php
    
    namespace My\Bundle\My\Namespace;
    
    use Symfony\Component\HttpFoundation\Session\Session;
    
    class SessionManager /* or whatever you want to call it */
    {
    
      public function __construct(Session $session)
      {
        $this->session = $session;
      }
    
      public function getMyValue()
      {
        return $this->session->get('my.value.key',null);
      }
    
      public function setMyValue($value)
      {
        $this->session->set('my.value.key',$value);
        return $this;
      }
      public function hasMyValue()
      {
        return $this->session->has('my.value.key');
      }
    }
    

    在你的 bundle services.yml 中

    <service id="mytag.session_manager" class="My\Bundle\My\Namespace\SesionManager">
        <argument type="service" id="session" />
    </service>
    

    在你的控制器中

    public function someAction()
    {
       $sessionManager = $this->get('mytag.session_manager');
    
      if($sessionManager->hasMyValue())
      {
        // do something
      }
    }
    

    【讨论】:

      【解决方案2】:

      感谢 Sgoettschkes 在这里的回答 Where to place common business logic for all pages in symfony2 我试过这个方法 http://symfony.com/doc/current/book/templating.html#embedding-controllers

      它看起来很棒: 我的 Popup 包含在这样的主模板中

      {{ render(controller('MalyutkaMainBundle:WelcomePopup:index')) }}

      比在控制器内部我操纵会话变量

      class WelcomePopupController extends Controller {
          public function indexAction(Request $request) {
              $session = $this->get('session');
      
              $showWelcomePopup = 0;
      
              if ($session->has("have_seen_welcome_popup_on")) {
                  // tbd compare to the date of publishing of the new popup screen 
              } else {
                  $showWelcomePopup = 1;
                  $session->set("have_seen_welcome_popup_on", new \DateTime());
              }
      
              $params = array (   
                  'show_welcome_popup' => $showWelcomePopup
              );
      
              return $this->render('MalyutkaMainBundle:WelcomePopup:welcome_popup.html.twig', $params);
          }
      }
      

      在其他控制器中不会添加任何内容——这正是我想要做的。 但是这种方式无法更改 cookie,所以我将数据存储在会话中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-31
        • 2017-11-23
        • 2020-02-22
        相关资源
        最近更新 更多