php - Can I give a Symfony 2 service the ability to read and write cookies? -
i have service should able read , write cookies. in symfony-like manner, service must have access request , response. can imagine it's possible pass request service through service configuration, don't know how. i'm not sure how i'm going give service ability write cookies though. suggestions on how appreciated.
note: don't want have manually pass variables service every time use it.
i think have couple of options - depends on trying store in cookie , @ point in process need read work.
i suggest first option create service, has access the request , creates response, returns ...
define service in services.yml :
services: a_service: class: acme\demobundle\requestserviceclass arguments: [@request] scope: request
your class :
//acme\demobundle\requestserviceclass.php class requestserviceclass { private $request; public function __construct(request $request){ $this->request= $request; } public function dosomething(){ // cookie $value = $this->request->cookies->get('cookie'); // create cookie $cookie = new cookie('cookie', 'value', time() + 3600 * 24 * 7); // create response $response = new response(); // set cookie in response $response->headers->setcookie($cookie); return $response; } }
then use service
public myaction() { $response = $this->get('a_service')->dosomething(); return $response; }
the other way of doing it, create kernel.response
listener ... done :
add service services.yml :
services: a_listener: class: acme\demobundle\mylistener tags: - { name: kernel.event_listener, event: kernel.response, method: onkernelresponse }
your listener class looks :
// acme\demobundle\mylistener.php class mylistener { public function onkernelresponse(filterresponseevent $event) { $response = $event->getresponse(); $request = $event->getrequest(); // cookie $value = $request->cookies->get('cookie'); // create cookie $cookie = new cookie('cookie', 'value', time() + 3600 * 24 * 7); // set cookie in response $response->headers->setcookie($cookie); } }
the difference between 2 methods information available @ time of process - example service has access pass ... response listener has access in request , response - check if response expected (ie format or content) , set cookie according that.
some links useful documentation read :
Comments
Post a Comment