Symfony 2 is great but it’s not well documented yet and there is no documentation about cookie handling as well.
After a few code digging I’ve found the solution. As we know, basically, cookies are just HTTP headers and you can get them from requests or send with responses.
SymfonyComponentHttpFoundationResponse class has a public property named headers and its type is ResponseHeaderBag and ResponseHeaderBag has a method named setCookie. Voilà!
Now we can set cookies like this:
$response = new Response();
$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));
return $this->render(‘template_path’, array(..template_parameters…), $response);
As you can see setCookie method needs a Cookie object as parameter and it’s located in SymfonyComponentHttpFoundation. You can create a cookie object like this:
new Cookie($name, $value = null, $expire = 0, $path = ‘/’, $domain = null, $secure = false, $httpOnly = true);