如何添加Cookie Magento 2?


Answers:


26

IMO最好的方法是创建一个类来包装cookie的创建,然后在需要的地方使用它。

Cookie类

{供应商} / {模块} /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($duration)
            ->setPath($this->sessionManager->getCookiePath())
            ->setDomain($this->sessionManager->getCookieDomain());

        $this->cookieManager->deleteCookie(
            self::COOKIE_NAME,
            $metadata
        );
    }
}

本示例基于Magento \ Framework \ App \ PageCache \ FormKey, 并表示一个名为“ example”的cookie

如果要向$ metadata(PublicCookieMetadata)添加一些自定义属性,以更改路径,http_only等,则应重构set()and / or delete()方法。

如何使用它

您几乎可以在几乎任何地方使用对象管理器来访问该类(丑陋的方法):

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->get('Vendor\Module\Cookie\Example')
    ->set('value', 3600);

根据您需要创建cookie的“位置”,您可以查看类的构造函数,也许您已经在那里有了一个对象管理器,如果没有的话,也可以将其注入构造函数中。


@J。约翰,嘿!我认为我在编辑答案时就接受了答案,现在就来看一下,因为我做了一些更改以简化实现。
MauroNigrele '16

3
我已经到编辑createCookieMetaData()createPublicCookieMetadata()set方法来解决错误(致命错误)。聪明的办法!
RT

Magento\Framework\Session\SessionManagerInterfaceMagento\Framework\Session\Config\ConfigInterface使用的与在中使用的有什么区别Magento\Framework\Session\SessionManager
LucScu'6

设置和删除方法中的@MauroNigrele函数调用应该是createPublicCookieMetadata而不是createCookieMetadata
Shivam

1
伙计们 我已经提出了更改建议,因为$this->createPublicCookieMetadata()该课程中不存在更改。它应该$this->cookieMetadataFactory->createPublicCookieMetadata() 在magento repo中看到。但是我有2个拒绝。大声笑...
旋转

-1

您可以使用php基本功能设置和获取Cookie,如下所示:

//set cookie
$cookie_name = "magento";
$cookie_value = "How to Cookie";
setcookie($cookie_name, $cookie_value, time()+3600); /* expire in 1 hour */

//get cookie
if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!<br>";
    echo "Value is: " . $_COOKIE[$cookie_name];
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.