Shopware 6:如何在自定义插件控制器中获取基础URL?
在Shopware 6自定义插件控制器中获取基础URL的正确方式
方案1:通过Request获取当前请求的基础URL
如果需要的是当前请求对应的域名,可以注入RequestStack直接获取:
use Symfony\Component\HttpFoundation\RequestStack; use Shopware\Core\Framework\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; #[Route(defaults: ['_routeScope' => ['storefront']])] class YourCustomController extends AbstractController { private RequestStack $requestStack; public function __construct(RequestStack $requestStack) { $this->requestStack = $requestStack; } #[Route(path: '/your-custom-path', name: 'frontend.your.custom.action', methods: ['GET'])] public function customAction() { $currentRequest = $this->requestStack->getCurrentRequest(); // 获取协议+域名,示例:https://your-shop.com $baseUrl = $currentRequest->getSchemeAndHttpHost(); // 若Shopware部署在子路径下,需拼接base path $fullBaseUrl = $baseUrl . $currentRequest->getBaseUrl(); } }
方案2:通过SalesDomainService获取销售渠道配置的域名
如果需要获取当前销售渠道后台配置的官方域名,推荐使用SalesDomainService,它会自动匹配当前上下文的销售渠道和对应域名:
use Shopware\Core\System\SalesChannel\SalesChannelContext; use Shopware\Core\System\SalesChannel\SalesDomainService; use Shopware\Core\Framework\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; #[Route(defaults: ['_routeScope' => ['storefront']])] class YourCustomController extends AbstractController { private SalesDomainService $salesDomainService; public function __construct(SalesDomainService $salesDomainService) { $this->salesDomainService = $salesDomainService; } #[Route(path: '/your-custom-path', name: 'frontend.your.custom.action', methods: ['GET'])] public function customAction(SalesChannelContext $context) { $salesDomain = $this->salesDomainService->getSalesDomain($context); // 获取配置的域名URL,示例:https://your-shop.com/ $baseUrl = $salesDomain->getUrl(); // 可选:去除URL末尾的斜杠 $baseUrl = rtrim($baseUrl, '/'); } }
你的原有代码失效的原因及修复
你使用的$salesChannel->getDomains()->first()->getUrl()无法工作,大概率是以下原因:
- 未加载domains关联数据:获取SalesChannel对象时,默认不会加载关联的域名数据,需要显式添加关联:
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; use Shopware\Core\System\SalesChannel\SalesChannelRepository; // 在控制器中注入SalesChannelRepository private SalesChannelRepository $salesChannelRepository; public function __construct(SalesChannelRepository $salesChannelRepository) { $this->salesChannelRepository = $salesChannelRepository; } // 在方法中获取带域名关联的SalesChannel public function yourAction(SalesChannelContext $context) { $criteria = new Criteria([$context->getSalesChannelId()]); // 必须添加domains关联,否则getDomains()返回空集合 $criteria->addAssociation('domains'); $salesChannel = $this->salesChannelRepository->search($criteria, $context->getContext())->first(); if ($salesChannel && $salesChannel->getDomains()->count() > 0) { $baseUrl = $salesChannel->getDomains()->first()->getUrl(); } }
- 当前销售渠道未配置域名:请登录Shopware后台,检查对应销售渠道的「域名」设置,确保已经添加并启用了有效域名。
内容的提问来源于stack exchange,提问作者Piyush Sapariya
相关产品推荐
相关产品推荐

