Symfony 4 启动会话

Symfony 4 start session

symfony 新手,我正在尝试开始我的第一个会话

这是我的全部代码,位于 public/php/session.php:

use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

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

我遇到错误 Uncaught Error: Class 'Symfony\Component\HttpFoundation\Session\Session' not found

phpstorm 没有报错,需要安装模块吗?我尝试了 composer require session 但那不起作用

我还在config/packages/framework.yaml

中用handler_id: ~尝试了symfony doc方法

使用此方法,没有错误消息,但也没有会话 cookie

这是我的控制器:

class HomeController extends AbstractController {

 // start session

  public function index(SessionInterface $session) {
   $session->set('foo', 'bar');
   $session->get('foo');
  }

  /**
  * @Route("/", name="home")
  */

  public function homepage(){
   return $this->render('home.html.twig');
  }

 }

如果您使用整个 symfony 框架,它会在您读取、写入甚至检查会话中是否存在数据时自动启动会话。您不需要手动执行此操作。

您需要做的是定义一个您将使用的适配器,或者将其留给 php 在

中配置

config/packages/framework.yaml

framework:
+     session:
+         # The native PHP session handler will be used
+         handler_id: ~

然后在您的服务中,控制器只获取会话服务

启用 SF4 和自动接线,在控制器操作中

public function index(SessionInterface $session)
{
       $session->set('foo', 'bar');
       $session->get('foo');
}

就是这样。在 https://symfony.com/doc/current/controller.html#session-intro

中查看更多信息

你的代码不在框架内,它不会工作,因为没有自动加载器可以从作曲家加载组件,如果你包含 vendor/autoload.php 它会工作但是不要走那条路。

正如@Robert 所提到的,由于您的代码在 public/php 中,因此它不知道自动加载器,它告诉 PHP 文件相对于它们的命名空间(PSR-0 或PSR-4).

我认为令人困惑的是你的 public index function 不会自动启动会话,因为它不会被 Symfony 调用,除非你导航到 index() 函数并且必须 return Response。尝试将会话传递给您的 homepage 方法参数并在浏览器中导航到它。

use Symfony\Component\HttpFoundation\Session\SessionInterface;

class HomeController extends AbstractController 
{

  /**
   * @Route("/", name="home")
   */
  public function homepage(SessionInterface $session)
  {
    $session->set('foo', 'bar');

    return $this->render('home.html.twig');
  }

 }