1
Mage::getModel('core/cookie')->set('visitor_id', $visitorId, $this->_getExpiryTime(), '/');

How to convert this code into magento2?

I have trying this:

 $this->_cookieManager->setCookie('visitor_id', $visitorId, $this->getExpiryTime(), '/'); 

But its shows error.

This is my fun():

public function generateVisitorId()
{
    $visitorId = $this->_checkoutSession->get('visitor_id');              
    if (!$visitorId) {
        $visitorId = uniqid();
        $this->_cookieManager->setCookie('visitor_id', $visitorId, $this->getExpiryTime(), '/');        
    }

    return $visitorId;
}
4

1 Answer 1

1

Here is a code from one of my modules:

use Magento\Framework\App\Helper\AbstractHelper as MagentoAbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Stdlib\CookieManagerInterface;

class Cookie extends MagentoAbstractHelper
{
    const DEFAULT_COOKIE_LIFETIME = 172800; // 2 days
    const CONNECTOR_COOKIE_NAME = 'CONNECTOR';

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Magento\Framework\Stdlib\CookieManagerInterface
     */
    protected $cookieManager;

    /**
     * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
     */
    protected $cookieMetadataFactory;

    /**
     * @var \Magento\Framework\Session\SessionManagerInterface
     */
    protected $sessionManager;

    /**
     * @param Context $context
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param CookieManagerInterface $cookieManager
     * @param CookieMetadataFactory $cookieMetadataFactory
     * @param SessionManagerInterface $sessionManager
     */
    public function __construct(
        Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        CookieManagerInterface $cookieManager,
        CookieMetadataFactory $cookieMetadataFactory,
        SessionManagerInterface $sessionManager
    ) {
        parent::__construct($context);
        $this->storeManager = $storeManager;
        $this->cookieManager = $cookieManager;
        $this->cookieMetadataFactory = $cookieMetadataFactory;
        $this->sessionManager = $sessionManager;
    }

    /**
     * Get data from cookie
     *
     * @return string
     */
    public function get()
    {
        $value = $this->cookieManager->getCookie($this->getCookieName());
        if ($this->isJson($value)) {
            $value = json_decode($value, true);
        }

        return $value;
    }

    /**
     * Set data to cookie
     *
     * @param string|array $value
     * @param int $duration
     *
     * @return void
     */
    public function set($value, $duration = null)
    {
        $metadata = $this->cookieMetadataFactory
            ->createPublicCookieMetadata()
            ->setDuration($duration ? $duration : static::DEFAULT_COOKIE_LIFETIME)
            ->setPath($this->sessionManager->getCookiePath())
            ->setDomain($this->sessionManager->getCookieDomain());
        if (is_array($value)) {
            $value = json_encode($value);
        }
        $this->cookieManager->setPublicCookie(
            $this->getCookieName(),
            $value,
            $metadata
        );
    }

    /**
     * delete cookie remote address
     *
     * @return void
     */
    public function delete()
    {
        $this->cookieManager->deleteCookie(
            $this->getCookieName(),
            $this->cookieMetadataFactory
                ->createCookieMetadata()
                ->setPath($this->sessionManager->getCookiePath())
                ->setDomain($this->sessionManager->getCookieDomain())
        );
    }

    /**
     * Used to get cookies name (key) by which data can be set or get
     *
     * @return string
     */
    public function getCookieName()
    {
        return static::CONNECTOR_COOKIE_NAME;
    }

    /**
     * Check string is valid JSON
     *
     * @source http://stackoverflow.com/questions/6041741/fastest-way-to-check-if-a-string-is-json-in-php
     * @param $string
     * @return bool
     */
    public function isJson($string)
    {
        json_decode($string);

        return (json_last_error() == JSON_ERROR_NONE);
    }
}

You can use this code to work with a cookies.

PS: CONNECTOR - name of my module.

7
  • const CONNECTOR_COOKIE_NAME = 'CONNECTOR';'CONNECTOR' means ...........
    – Mahi M
    Commented Dec 11, 2017 at 7:14
  • @MahalakshmiM This is just a cookie name of my module, change it to your cookie name. Commented Dec 11, 2017 at 7:15
  • How to call duration() inside set()
    – Mahi M
    Commented Dec 11, 2017 at 7:50
  • @MahalakshmiM duration() - method of some class? Commented Dec 11, 2017 at 7:52
  • @MahalakshmiM I'm glad to help you :) Commented Dec 11, 2017 at 8:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.