简体   繁体   English

在主页中获取客户 ID - Magento 2

[英]Get Customer ID in Home Page - Magento 2

I need to get the Customer ID primary in Home Page, but not have a Session Interface to give this information.我需要在主页中获取主要的客户 ID,但没有 Session 接口来提供此信息。

I tried theses:我试过论文:

\Magento\Backend\Model\Session
\Magento\Catalog\Model\Session
\Magento\Checkout\Model\Session
\Magento\Customer\Model\Session
\Magento\Newsletter\Model\Session

Exists one interface to give Customer ID on every page ?是否存在一个界面以在每一页上提供客户 ID?

There are methods available in magento2 to get customer id, one of the method is using Object Manager as below code. magento2 中有一些方法可以获取客户 ID,其中一种方法是使用 Object Manager 如下代码。

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();  
$customerSession = $objectManager->get('Magento\Customer\Model\Session');  
$customerId = $customerSession->getCustomer()->getId(); // get the customer Id

namespace Vendor\Module\Block;命名空间供应商\模块\块;

class Form extends \Magento\Framework\View\Element\Template class 表单扩展\Magento\Framework\View\Element\Template

    protected $customerSession;

    /**
     * Construct
     *
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Customer\Model\Session $customerSession
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        array $data = []
    ) {
        parent::__construct($context, $data);

        $this->customerSession = $customerSession;
    }

    public function _prepareLayout()
    {

        var_dump($this->customerSession->getCustomer()->getId());
        exit();
        return parent::_prepareLayout();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM