Thursday, August 4, 2011

Redirection with Cookie sending in Symfony2

As i apply a redirection after switching language, i'd like to send a cookie to store the last selected language for the user. But Symfony2 RedirectResponse default constructor doesn't allow to do this....

Here is a class extanding RedirectResponse that takes an array of Cookie objects as third parameters :

This component is downloadable and forkable on my Git repository : http://github.com/alterphp/components

<?php

/*
 * A RedirectResponse object with cookie sending
 */

namespace AlterPHP\Component\HttpFoundation;

use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * RedirectResponseWithCookie represents an HTTP response doing a redirect and sending cookies.
 */
class RedirectResponseWithCookie extends RedirectResponse
{

   /**
    * Creates a redirect response so that it conforms to the rules defined for a redirect status code.
    *
    * @param string  $url    The URL to redirect to
    * @param integer $status The status code (302 by default)
    * @param Symfony\Component\HttpFoundation\Cookie[] $cookies An array of Cookie objects
    */
   public function __construct($url, $status = 302, $cookies = array ())
   {
      parent::__construct($url, $status);

      foreach ($cookies as $cookie)
      {
         if (!$cookie instanceof Cookie)
         {
            throw new \InvalidArgumentException(sprintf('Third parameter is not a valid Cookie object.'));
         }
         $this->headers->setCookie($cookie);
      }
   }
}

Example :

/* in a controller action */

$cookie = new Cookie('Language', $culture, '2037-01-01');

return new RedirectResponseWithCookie($this->generateUrl($route, $params), 302, array ($cookie));

2 comments :

ardian said...

You can review this

http://www.craftitonline.com/2011/07/symfony2-how-to-set-a-cookie/

Unknown said...

works perfect. nice... thank you a lot. Help me to use less time.

Post a Comment

Comments are moderated before being published.