【问题标题】:Session conditions in a symfony2 controllersymfony2 控制器中的会话条件
【发布时间】:2014-01-17 13:59:10
【问题描述】:

在使用 symfony2 时,我想显示不同的布局(base.html.twig 用于访客,layout.html.twig 用于登录用户)。

当用户连接到他的帐户时,他还可以(就像 facebook 一样)“连接为”一个页面或一个组(总是在他的帐户内),对于这两个我还必须显示不同的布局( pagelayout.html.twig 和 grouplayout.html.twig)。

似乎解决方案是创建一个控制器(例如 indexAction),其中包含会话和数据库查询的所有条件。

例如(为了简化,我改了代码):

public function indexAction(){

     // ...
     if (!$mySession) { //the user is not connected          
         //redirection to home controller that uses base.twig.html          
     } else {  //the user is logged in
          if ($connectAs=='profile') {
                  //redirection to home controller that uses layout.twig.html   
          } else if($connectAs=='page') {
                 //redirection to page controller that uses pagelayout.twig.html  
          } else if($connectAs=='group') {
                 //redirection to group controller that uses grouplayout.twig.html
          }
     }
}

我想在一个重定向控制器中使用这些条件,但我认为这不是一个灵活的解决方案。因为我可以集成其他类型的布局和控制器,我可能需要添加更多的条件。

有没有更好的解决方案,比可以更灵活?

Edit :这个解决方案的另一个问题是,即使用户作为 "Page" 连接,他仍然可以输入到 Group 或 User 控制器的路由的 URL 并获取也可以访问它们...除非我也在这些控制器中添加了条件。

我真正需要的是创建一个像 frontController 一样的控制器

【问题讨论】:

  • 你为什么不直接设置一个$template 变量并将其传递给控制器​​的渲染函数?
  • 因为,这不仅仅是布局的问题,也是数据库数据的问题,页面和组的表以及它们的查询不同,这就是为什么我需要使用不同的控制器分开的捆绑包
  • 所以,我想我需要创建一个类似于 frontController 的东西,它处理这些数据并决定执行哪个控制器。
  • 但这就是你已经拥有的,我不明白我猜的问题。 ://
  • 也许您可以使用多个防火墙。

标签: php symfony redirect layout controller


【解决方案1】:

如果你想要一个类似逻辑的前端控制器,你需要用一个控制器捕获所有可能的路由,然后从那里转发。

# all other routed efinitions should go above this,
# so that _frontcontroller acts like a fallback

_frontcontroller:
    path:     /{url}
    defaults: { _controller: YourFrontBundle:Front:index }
    requirements:
        name: ".+" #allow / in the route

然后您的控制器应根据条件和 url 转发给控制器

public function indexAction($url)
{
    // ...
    } else if ($connectAs=='group') {
        $this->forward('YourGroupBundle:Group:index');
        // or something else based on the url parameter
    }
    // ...
}

还有带有dynamic routing 的 CMF Bundle,但我还没有深入研究。

【讨论】:

  • 是的,我的朋友,非常感谢……这正是我所需要的,我将转发我的控制器。再次感谢。 +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 2023-03-16
  • 2015-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多