[英]Sylius - Dynamic change of channels from the client group
我来自 Magento,我现在使用 Sylius 来使事情稍微现代化,并且可以访问一个不太面向 xml 的平台,因为我发现在 2022 年它真的很痛苦......
不幸的是,我没有在 Sylius 中找到任何关于根据当前登录的客户管理价格的信息。
所以我想使用组和频道:我向用户组添加了频道关系,以便能够根据登录用户使用频道。
/**
* @ORM\Entity
* @ORM\Table(name="sylius_customer_group")
*/
class CustomerGroup extends BaseCustomerGroup
{
/**
* @ORM\ManyToOne(targetEntity=Channel::class)
*/
private $channel;
public function getChannel(): ?Channel
{
return $this->channel;
}
public function setChannel(?Channel $channel): self
{
$this->channel = $channel;
return $this;
}
}
这是我想用服务做的
services:
ChangingContextWithCustomerGroup:
class: App\Context\RequestQueryChannelContext
arguments:
- '@sylius.repository.channel'
- '@request_stack'
- '@sylius.context.customer'
tags:
- { name: sylius.context.channel, priority: 150 }
// src/Context/RequestQueryChannelContext.php
public function getChannel(): ChannelInterface
{
$request = $this->requestStack->getMainRequest();
if (!$request) {
throw new ChannelNotFoundException('Request Not Found!');
}
$customer = $this->customerContext->getCustomer();
if (!$customer instanceof Customer) {
throw new ChannelNotFoundException('Customer Not Found!');
}
$group = $customer->getGroup();
if (!$group instanceof CustomerGroup) {
throw new ChannelNotFoundException('Group Not Found!');
}
$channel = $group->getChannel();
if (!$channel instanceof ChannelInterface) {
throw new ChannelNotFoundException('Channel Not Found!');
}
return $channel;
}
我的问题是我无法在 mainRequest 上获得客户。 它是 null,所以我不能有客户 => 组 => 频道。
当我像这样强制频道时,它工作得很好:
public function getChannel(): ChannelInterface
{
// ...
return $this->channelRepository->findOneByCode('fooBar');
}
所以我的系统不工作。 有更好的解决方案吗?
谢谢
这里的问题是 Channel 上下文是从Sylius\Bundle\ShopBundle\EventListener\NonChannelLocaleListener
的,它在kernel.request
事件上具有优先级 10。 在通道上下文中,您要使用客户上下文 class,后者又使用TokenStorage
检索用户信息。 然而,此时令牌尚未填充到令牌存储中,因为这发生在防火墙侦听器(开发环境中的Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener
)中,优先级为 8。
我找到的解决方案是将NonChannelLocaleListener
的优先级降低到 7。这将确保令牌可用并且客户上下文可用于检索客户/商店用户信息。
可以通过覆盖config/services.yaml
中的服务定义来降低该侦听器的优先级:
services:
...
sylius.listener.non_channel_request_locale:
class: Sylius\Bundle\ShopBundle\EventListener\NonChannelLocaleListener
arguments:
- '@router'
- '@sylius.locale_provider'
- '@security.firewall.map'
- ['%sylius_shop.firewall_context_name%']
tags:
- { name: kernel.event_listener, event: kernel.request, method: restrictRequestLocale, priority: 7 }
请注意,这是在 Sylius 1.10 上进行的,因此在其他 Sylius 版本上,这些侦听器的优先级可能略有不同。 在这种情况下,只需使用bin/console debug:event-dispatcher
命令来确定正确的优先级应该是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.