我试图开始(或访问)这样的会话:
$session = new Session();
echo $session->getId();
根据文档应该是我需要的,因为会话自动启动(http://symfony.com/doc/master/components/http_foundation/sessions.html):
While it is recommended to explicitly start a session, a sessions will actually start
on demand, that is, if any session request is made to read/write session data.
然而,我得到了错误
Failed to start the session because headers have already been sent.
这是调用该服务的原始控制器:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\Response;
$auth = $this->get('authentication');
$user_id = $auth->getUserId();
然后是getUserId函数:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
public function getUserId() {
$session = new Session();
echo $session->getId();
如果我将getUserId更改为如下所示:
public function getUserId() {
$session = $this->getRequest()->getSession();
echo $session->getId();
我收到错误:
Call to a member function get() on a non-object
答案 0 :(得分:2)
您正在查看独立组件“HTTP Foundation”的文档。这意味着在使用全栈框架symfony2时必须非常小心。
Symfony2已经处理了请求/响应和会话,因此您不需要创建任何Session对象。您可以在常规文档章节Controller中阅读有关如何使用会话的信息。
要访问控制器中的会话,您只需要
$session = $this->getRequest()->getSession();
如果要访问服务中的会话,则需要在service.yml中将服务“请求”作为依赖项传递,然后通过
访问会话$session = $request->getSession();
如果您不习惯,Service Container章节有一些说明。