symfony 新手,我正在尝试开始我的第一次 session
这是我位于 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
但这不起作用我还用
handler_id: ~
尝试了 symfony doc 方法在 config/packages/framework.yaml
使用此方法,没有错误消息,但也没有 session cookie
这是我的 Controller :
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');
}
}
最佳答案
正如@Robert 所提到的,由于您的代码在 public/php
内它不知道自动加载器,它告诉 PHP 文件相对于它们的命名空间(PSR-0 或 PSR-4)的位置。
我相信困惑是你的 public index function
不会自动启动 session ,因为它不会被 Symfony 调用,除非您导航到 index()
函数并且必须返回 Response
.尝试将 session 传递给您的 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');
}
}
关于php - Symfony 4 启动 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51746683/