如何在Shopware 6前台控制器或订阅器中检查用户是否登录?
Shopware 6前台检查用户登录的方法(插件开发场景)
问题描述
我正在开发Shopware 6插件(非应用),希望在控制器和/或订阅器中实现前台用户登录状态检查,想确认以下三种方式是否可行:
- 使用Storefront API?具体如何操作?调用路径是什么?
- 使用Symfony默认的isGranted方法?应使用哪些角色?角色处理机制是否存在差异?
- 通过依赖注入获取内置的特殊服务?具体是哪个服务?
解决方案及说明
订阅器实现示例
感谢@Uwe Kleinmann的思路,以下是在订阅器中实现登录状态检查的代码:
public static function getSubscribedEvents() { return [ ProductPageLoadedEvent::class => 'onProductPageLoaded' ]; } public function onProductPageLoaded(ProductPageLoadedEvent $event): void { $saleschannelContext = $event->getSaleschannelContext(); $customer = $saleschannelContext->getCustomer(); if(null === $customer) { $customer = 'not-logged-in'; } $event->getPage()->addExtension( 'myextension', new ArrayStruct([ 'test' => $customer ]) ); }
三种方式的可行性说明
Storefront API方式
Storefront API主要面向前端交互场景,插件后端开发中不推荐使用。若在前端调用,可请求/store-api/account/customer路径:返回有效用户数据则表示已登录,返回空或错误则未登录。但后端控制器/订阅器中无需通过API,直接通过上下文获取用户信息更高效。Symfony isGranted方法
在Storefront控制器中可以直接使用Symfony的isGranted()方法,对应角色为ROLE_USER。Shopware已适配Symfony的角色机制,已登录用户会自动被赋予ROLE_USER角色,示例代码:
if ($this->isGranted('ROLE_USER')) { // 用户已登录逻辑 }
- 依赖注入内置服务
- 最常用的方式是通过
SalesChannelContext获取用户信息:在订阅器中可从事件对象直接获取(如上述示例),在控制器中可通过依赖注入或方法参数注入该对象,调用$saleschannelContext->getCustomer(),返回null则用户未登录,否则为已登录状态。 - 也可注入
Shopware\Core\System\Customer\CustomerSessionService服务,调用其getCustomer()方法获取当前用户信息,以此判断登录状态。
内容的提问来源于stack exchange,提问作者Steve Krämer
相关产品推荐
相关产品推荐

