Reputation: 1828
New to symfony, I am trying to start my first session
here is my entire code situated under public/php/session.php
:
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
$session = new Session();
$session->start();
I am getting error Uncaught Error: Class 'Symfony\Component\HttpFoundation\Session\Session' not found
phpstorm gives no error, do I need to install a module ? I tried composer require session
but that does not work
I also tried the symfony doc method with handler_id: ~
in config/packages/framework.yaml
with this method, no error message but no session cookie either
and here is my 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');
}
}
Upvotes: 5
Views: 11285
Reputation: 18416
As mentioned by @Robert, since your code is within public/php
it is not aware of the autoloader, which tells PHP where files are located in relation to their namespaces (PSR-0 or PSR-4).
I believe the confusion is that your public index function
does not automatically start the session, as it is not called by Symfony unless you navigate to the index()
function and must return a Response
. Try passing the session to your homepage
method arguments and navigating to it in the browser.
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');
}
}
Upvotes: 1
Reputation: 20286
If you use whole symfony framework it starts the sessions are automatically started whenever you read, write or even check for the existence of data in the session. You don't need to do that manually.
What you need to do is to define an adapter that you'll use or leave it to php configruation in
config/packages/framework.yaml
framework:
+ session:
+ # The native PHP session handler will be used
+ handler_id: ~
and then in your services, controlers just get session service
with SF4 and auto wiring enabled, in controller action
public function index(SessionInterface $session)
{
$session->set('foo', 'bar');
$session->get('foo');
}
that's all. See more in https://symfony.com/doc/current/controller.html#session-intro
Your code is not within the framework and it won't work because there's no autoloader which would load the component from composer, it'd work if you included vendor/autoload.php but don't go that way.
Upvotes: 2