Установить печенье в Magento2?


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

Как преобразовать этот код в magento2?

Я попробовал это:

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

Но это показывает ошибку.

Это мой fun():

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

    return $visitorId;
}
Author: Siarhey Uchukhlebau, 2017-12-11

1 answers

Вот код из одного из моих модулей:

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);
    }
}

Вы можете использовать этот код для работы с файлами cookie.

PS: СОЕДИНИТЕЛЬ - имя моего модуля.

 1
Author: Siarhey Uchukhlebau, 2017-12-11 07:53:43