我正在尝试在module.php内的第二个页面请求中设置一个cookie。我的页面请求会话setter工作正常,但不知道cookie没有设置。有没有解释为什么没有设置这个cookie?
Module.php
public function onBootstrap(MvcEvent $e)
{
$application = $e->getApplication();
$eventManager = $application->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener ->attach($eventManager);
$serviceManager = $application->getServiceManager();
//..
if (php_sapi_name() !== 'cli') {
//....
$this->_setUserTrackingCookie($serviceManager);
}
}
private function _setUserTrackingCookie($serviceManager)
{
$request = $serviceManager->get('Request');
$headers = $request->getHeaders();
$cookies = $request->getCookie();
if (!$cookies->offsetExists('fzz')) {
$acceptingCookies = new Container('fzz');
if (!$acceptingCookies->offsetExists('requests')) {
$acceptingCookies->offsetSet('requests', 1);
} else {
$cookieSalt = Rand::getString(32, 'abcdefghijklmnopqrstuvwxyz1234567890', true);
$dbAdapter = $serviceManager->get('Zend\Db\Adapter\Adapter');
$table = new \Application\Model\UserCookieTable($dbAdapter);
$userCookie = new UserCookie();
$userCookie->salt = $cookieSalt;
$userCookie->country = $country;
$table ->insertUserCookie($userCookie);
$locationCookie = new SetCookie('fzz', 'testing_cookie', strtotime('+1 Year', time()), '/');
$headers ->addHeader($locationCookie);
}
}
}
答案 0 :(得分:0)
稍微调低代码,cookie设置部分显示为:
$request = $serviceManager->get('Request');
$headers = $request->getHeaders();
$locationCookie = new SetCookie('fzz', 'testing_cookie', strtotime('+1 Year', time()), '/');
$headers->addHeader($locationCookie);
您正在向Representation of the Request
添加Cookie。虽然这对于表示非常好,但我们实际上无法修改请求。
您实际想要做的是将Cookie标头添加到Response
:
$response = $serviceManager->get('Response');
$headers = $response ->getHeaders();
$locationCookie = new SetCookie('fzz', 'testing_cookie', strtotime('+1 Year', time()), '/');
$headers->addHeader($locationCookie);
顺便提一下Zf-way
检查实际的HTTP请求:
if ($request instanceof \Zend\Http\PhpEnvironment\Request) {
$headers = $response ->getHeaders();
$locationCookie = new SetCookie('fzz', 'testing_cookie', strtotime('+1 Year', time()), '/');
$headers->addHeader($locationCookie);
}
在CLI上,$request
将成为Zend\Console\Request
的实例。