ZF2 - 在调度侦听器中设置cookie

时间:2016-08-25 07:23:20

标签: php cookies zend-framework2

我想在监听器中设置一个cookie,如果查询参数" source"已设定。我尝试了以下但cookie不存在。

如何正确设置Cookie?

app.directive('dndDragStart', function(dragService){

return{
restrict: 'A',
link :function(scope, elem, attr){

  elem.on('dragstart', function(event){
    console.log(event.target.id +"start");
    event = event.originalEvent || event;
     event.dataTransfer.effectAllowed = 'move';
    dragService.setDragItemId(event.target.id);   //here you go
  });     
 } 
};
});

---------------------------------更新------------- ----------------------

class DispatchListener extends AbstractListenerAggregate {

    public function attach(EventManagerInterface $eventManager) {
        $this->listeners[] = $eventManager->getSharedManager()->attach(
            'Zend\Stdlib\DispatchableInterface',
            MvcEvent::EVENT_DISPATCH, 
            array($this, 'setCookie'), 
            -80
        );
    }

    /**
     * @var \Zend\Stdlib\RequestInterface
     */
    protected $request;

    /**
     * @param \Zend\Stdlib\RequestInterface $request
     */
    public function __construct(RequestInterface $request) {
        $this->request = $request;
    }

    public function setCookie(EventInterface $event) {
        if ($source = $this->request->getQuery('source')) {
            $this->request->setCookies([
                'source' => $source
            ]);
        }
    }

} 

2 个答案:

答案 0 :(得分:1)

您是否希望在请求对象中使用cookie,或者是否要为响应创建cookie。您可能想要创建一个cookie并将其设置在响应对象上 检查例如this answer

public function setCookie(EventInterface $event) {
    if ($source = $this->request->getQuery('source')) {
        $cookie = new \Zend\Http\Header\SetCookie('source', $source);
        $headers = $this->getResponse()->getHeaders();
        $headers->addHeader($cookie);
    }
}

答案 1 :(得分:1)

似乎您的代码存在一些问题,我们可以先排除这些问题。

  • 您尚未提供有关如何附加听众的代码
  • 不确定为什么要在请求中设置cookie,是否要在响应中执行此操作?

附加事件监听器:

public function onBootstrap(MvcEvent $e)
{
  $eventManager = $e->getApplication()->getEventManager();
  $app  = $e->getApplication();
  $em = $app->getEventManager();

  // Attach event to attach listener after routing when query will be populated
  $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($eventManager) {
    $request = $e->getRequest();
    // attach our listener 
    $eventManager->attach(new DispatchListener($request));
  });
}

更新了setCookie方法:

public function setCookie(EventInterface $event) { 
    if ($source = $this->request->getQuery('source')) {
        $this->request->setCookies([
            'source' => $source
        ]);

        $request = $this->request;
        $cookieData = $request->getCookie('someCookie', 'default');
        var_dump($cookieData);
    }
}

var_dump打印以下内容:

object(Zend\Http\Header\Cookie)[274]
  protected 'encodeValue' => boolean true
  private 'storage' (ArrayObject) => 
    array (size=1)
   'source' => string 'test' (length=4)