繁体   English   中英

如何在Symfony2中为所有控制器设置会话变量?

[英]How to set session variables for all the controllers in Symfony2?

如何在控制器中创建和访问Symfony 2会话变量。 我曾经这样。

$session = new Session();
$session->start();
$session->set('loginUserId',$user['user_id']);

我想知道如何在所有控制器中使用以上会话变量进行访问。

在控制器中的Symfony中使用会话的一种方法是:

设置:

$this->get('session')->set('loginUserId', $user['user_id']);

得到:

$this->get('session')->get('loginUserId');

如果使用标准框架版本

从文档:

Symfony会话旨在替换一些本地PHP函数。 应用程序应避免使用session_start(),session_regenerate_id(),session_id(),session_name()和session_destroy(),而应使用以下部分中的API。

和:

虽然建议显式启动会话,但是实际上会根据需要启动会话,也就是说,如果发出任何会话请求来读取/写入会话数据。

因此,会话将自动启动,并且可以通过以下方式从控制器进行访问:

public function indexAction(Request $request)
{
    $session = $request->getSession();
    ...
}

要么:

public function indexAction()
{
    $session = $this->getRequest()->getSession();
    // or
    $session = $this->get('session');
    ...
}

比:

// store an attribute for reuse during a later user request
$session->set('foo', 'bar');

// get the attribute set by another controller in another request
$foobar = $session->get('foobar');

// use a default value if the attribute doesn't exist
$filters = $session->get('filters', array());

http://symfony.com/doc/current/components/http_foundation/sessions.html

  use Symfony\Component\HttpFoundation\Session\Session;

  $session = new Session();
  $session->start();

  // set and get session attributes
  $session->set('name', 'Drak');
  $session->get('name');

  // set flash messages
  $session->getFlashBag()->add('notice', 'Profile updated');

  // retrieve messages
     foreach ($session->getFlashBag()->get('notice', array()) as $message) {
     echo '<div class="flash-notice">'.$message.'</div>';
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM