0

I need to create a cookie in my service

public function __construct(EntityManager $em, RequestStack $request)
{
    parent::__construct();

    $this->request = $request->getMasterRequest();
}

then when I try to call this somewhere inside my service:

    echo $this->request->cookies->get('_ga');die;

I get cookie that's created manually by me, but calling ->set(key, val) doesn't save my cookie

 $this->request->cookies->set('test', time());
echo $this->request->cookies->get('test');

I get time, but cookie only exists once, in scope of this webrequest, if I comment line with ->set then I should see time that isn't changing but I don't see it, because cookie isn't actually stored... any help?

Denis Wróbel
  • 131
  • 1
  • 10

1 Answers1

1

Maybe you should try setting the cookies to the response Object that is used to build an answer - rather than the request which is what you received from the client.

Have a look at this post, it is for Simfony 2 but I assume the principle should be similar for 3.

Symfony2: setting a cookie

$response->headers->setCookie(new Cookie("user", $user));

Moreover I don't think you should set a Cookie in your service, try to pass all required information as business data classes to the service and return a class which can be used to formulate the response object including the cookie.

Benjamin Peter
  • 4,009
  • 2
  • 23
  • 23