【发布时间】:2016-12-03 19:02:30
【问题描述】:
我有一个监听器来监听<event name="controller_action_predispatch"> 事件。
观察者的execute方法在每个请求上都正确运行,但是启用缓存时Cookies设置不正确,更具体的Full Page Cache.(System -> Cache Management -> Page Cache)。
现在,当我禁用缓存时,cookie 已按预期设置,但从产品列表页面将商品添加到购物车时,右上角的迷你购物车保持空白。实际查看迷你购物车中的商品并能够结帐的唯一方法是首先转到随机产品概览页面,然后从那里将其添加到购物车中。有什么想法吗?
在观察者内部设置 Cookie:
$cookieManager->setPublicCookie('Custom_Cookie', 'This is a Cookie');
观察者类:
class MyObserver implements ObserverInterface {
protected $messageManager;
protected $cart;
protected $scopeConfig;
protected $logger;
public function __construct(
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Checkout\Model\Cart $cart,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Psr\Log\LoggerInterface $logger
) {
$this->messageManager = $messageManager;
$this->cart = $cart;
$this->scopeConfig = $scopeConfig;
$this->logger = $logger;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cookieManager = $objectManager->get('Magento\Framework\Stdlib\CookieManagerInterface');
$customer = $objectManager->create('Magento\Customer\Model\Customer');
$product = $objectManager->create('Magento\Catalog\Model\Product');
$cart = $objectManager->get('Magento\Checkout\Model\Cart');
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
// COOKIE
$cookieManager->setPublicCookie('Custom_Cookie', 'This is a Cookie');
$this->logger->info('COOKIE IS ==> ' . $cookieManager->getCookie('Custom_Cookie'));
...
}
【问题讨论】:
标签: php magento caching cookies observers