Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CatalogProductViewObserver.php
Go to the documentation of this file.
1 <?php
7 
10 
15 {
19  protected $_storeManager;
20 
25 
29  protected $_customerSession;
30 
34  protected $_customerVisitor;
35 
39  protected $eventSaver;
40 
44  private $reportStatus;
45 
53  public function __construct(
54  \Magento\Store\Model\StoreManagerInterface $storeManager,
55  \Magento\Reports\Model\Product\Index\ViewedFactory $productIndxFactory,
56  \Magento\Customer\Model\Session $customerSession,
57  \Magento\Customer\Model\Visitor $customerVisitor,
59  \Magento\Reports\Model\ReportStatus $reportStatus
60  ) {
61  $this->_storeManager = $storeManager;
62  $this->_productIndxFactory = $productIndxFactory;
63  $this->_customerSession = $customerSession;
64  $this->_customerVisitor = $customerVisitor;
65  $this->eventSaver = $eventSaver;
66  $this->reportStatus = $reportStatus;
67  }
68 
75  public function execute(\Magento\Framework\Event\Observer $observer)
76  {
77  if (!$this->reportStatus->isReportEnabled(Event::EVENT_PRODUCT_VIEW)) {
78  return;
79  }
80 
81  $productId = $observer->getEvent()->getProduct()->getId();
82 
83  $viewData['product_id'] = $productId;
84  $viewData['store_id'] = $this->_storeManager->getStore()->getId();
85  if ($this->_customerSession->isLoggedIn()) {
86  $viewData['customer_id'] = $this->_customerSession->getCustomerId();
87  } else {
88  $viewData['visitor_id'] = $this->_customerVisitor->getId();
89  }
90 
91  $this->_productIndxFactory->create()->setData($viewData)->save()->calculate();
92 
93  $this->eventSaver->save(Event::EVENT_PRODUCT_VIEW, $productId);
94  }
95 }
$storeManager
execute(\Magento\Framework\Event\Observer $observer)
__construct(\Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Reports\Model\Product\Index\ViewedFactory $productIndxFactory, \Magento\Customer\Model\Session $customerSession, \Magento\Customer\Model\Visitor $customerVisitor, EventSaver $eventSaver, \Magento\Reports\Model\ReportStatus $reportStatus)