How to add Cookie Magento 2?
IMO the best approach would be to create a class to wrap the cookie creation and then just use it where you want.
The Cookie Class
{Vendor}/{Module}/Cookie/Example.php
<?php
namespace Vendor\Module\Cookie;
use Magento\Framework\Stdlib\CookieManagerInterface;
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Session\SessionManagerInterface;
class Example
{
/**
* Name of cookie that holds private content version
*/
const COOKIE_NAME = 'example';
/**
* CookieManager
*
* @var CookieManagerInterface
*/
private $cookieManager;
/**
* @var CookieMetadataFactory
*/
private $cookieMetadataFactory;
/**
* @var SessionManagerInterface
*/
private $sessionManager;
/**
* @param CookieManagerInterface $cookieManager
* @param CookieMetadataFactory $cookieMetadataFactory
* @param SessionManagerInterface $sessionManager
*/
public function __construct(
CookieManagerInterface $cookieManager,
CookieMetadataFactory $cookieMetadataFactory,
SessionManagerInterface $sessionManager
) {
$this->cookieManager = $cookieManager;
$this->cookieMetadataFactory = $cookieMetadataFactory;
$this->sessionManager = $sessionManager;
}
/**
* Get form key cookie
*
* @return string
*/
public function get()
{
return $this->cookieManager->getCookie(self::COOKIE_NAME);
}
/**
* @param string $value
* @param int $duration
* @return void
*/
public function set($value, $duration = 86400)
{
$metadata = $this->cookieMetadataFactory
->createPublicCookieMetadata()
->setDuration($duration)
->setPath($this->sessionManager->getCookiePath())
->setDomain($this->sessionManager->getCookieDomain());
$this->cookieManager->setPublicCookie(
self::COOKIE_NAME,
$value,
$metadata
);
}
/**
* @return void
*/
public function delete()
{
$metadata = $this->cookieMetadataFactory
->createPublicCookieMetadata()
->setDuration(0)
->setPath($this->sessionManager->getCookiePath())
->setDomain($this->sessionManager->getCookieDomain());
$this->cookieManager->deleteCookie(
self::COOKIE_NAME,
$metadata
);
}
}
This example was based on Magento\Framework\App\PageCache\FormKey and represent a single cookie with name "example"
If you want to add some custom properties to the $metadata (PublicCookieMetadata) as change the path,http_only, etc you should refactor the set()
and/or delete()
method(s).
How to use it
You can access that class simply using the Object Manager in almost anywhere (Ugly Approach):
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->get('Vendor\Module\Cookie\Example')
->set('value', 3600);
Depending "where" you need to create the cookie you can take a look at the constructor of your class maybe you already have an Object manager there, if not you can also inject it in the constructor.