当前位置: 技术文章>> Magento 2:如何检查客户是否已登录?

文章标题:Magento 2:如何检查客户是否已登录?
  • 文章分类: Magento
  • 11463 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


检查客户是否在Magento 2中登录的步骤:

我们可以使用以下方法检查客户是否已在Magento 2中登录。

让我们开始吧,

方法 1: 使用帮助程序文件

在以下路径处创建帮助程序文件。

app/code/Vendor/Extension/Helper/Data.php

然后添加代码,如下所示

<?php
 
namespace Vendor\Extension\Helper;
 
class Data
{
    public function __construct(
       \Magento\Framework\App\Http\Context $httpContext
    ) {
        $this->httpContext = $httpContext;
    }
 
    public function getLogin() {
        return $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
    }
?>

注意 – 根据您的要求,您可以在 phtml、控制器等中使用 getLogin() 方法。

方法 2:使用对象管理器

在您的Magento根目录中创建customer.php。

{{magento_root}}/customer.php

现在,添加以下代码

<?php
 
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
 
try
{
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('\Magento\Framework\App\State');
    $appState->setAreaCode('frontend');
 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $userContext = $objectManager->get('Magento\Framework\App\Http\Context');
    $loggedin = $userContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
   
    if($loggedin) {
      echo "Customer is Logged-In";
    }
}
catch(\Exception $e)
{
    print_r($e->getMessage());
}

结论:

因此,使用上述方法,您可以轻松确定登录到Magento 2商店的客户。


推荐文章