2016-09-23 85 views
1

我想在module.php裏的第二個頁面請求中設置一個cookie。我的頁面請求會話設置程序運行良好,但不知何故cookie未設置。有沒有解釋爲什麼這個cookie沒有設置?ZF2在模塊內設置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

修邊下來你的代碼一點點,該cookie設置部分內容:

$request = $serviceManager->get('Request'); 
$headers = $request->getHeaders(); 
$locationCookie = new SetCookie('fzz', 'testing_cookie', strtotime('+1 Year', time()), '/'); 
$headers->addHeader($locationCookie); 

你添加一個cookie的Representation of the Request。雖然這對於表示很好,但我們實際上無法修改請求。

你真正想要做的是Cookie的標頭添加到Response代替:

$response = $serviceManager->get('Response'); 
$headers = $response ->getHeaders(); 
$locationCookie = new SetCookie('fzz', 'testing_cookie', strtotime('+1 Year', time()), '/'); 
$headers->addHeader($locationCookie); 

有順便說一下檢查是否有實際的HTTP請求的更Zf-way

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的實例。