Search code examples
cookiessymfony1model

Symfony: set cookie from model?


Is it possible to set (or retrieve) cookies from the model layer?

Granted that the model layer is intended for 'business logic', the logic I need requires a little interaction with the request and response.


Solution

  • I suggest you process and store your cookie value in your model:

    class ModelTable
    {
      protected $cookie = null;
    
      public function getCookie()
      {
        return $this->cookie;
      }
    
      public function setCookie($value)
      {
        $this->cookie = $value;
      }
    }
    

    And use postExecute of your action to set cookie:

    class yourActions extends sfActions
    {
      public function executeIndex(sfWebRequest $request)
      {
        ModelTable::getInstance()->setCookie('bla');
      }
    
      public function postExecute()
      {
        $cookie = ModelTable::getInstance()->getCookie();
        $this->getResponse()->setCookie('name', $cookie, time() + 24 * 3600);
      }
    }
    

    It's always better to stick to MVC model: controller calls model for info and build the response, not the other way around.