我正在根据请求uri更改会话的cookie_path选项。
config/framework.yaml
framework:
session:
storage_factory_id: session.storage.factory.native
cookie_path: '/admin'
App/EventSubscriber/SessionSubscriber.php
class SessionSubscriber implements EventSubscriberInterface
{
private SessionStorageInterface $storage;
public function __construct(SessionStorageInterface $storage)
{
$this->storage = $storage;
}
public static function getSubscribedEvents(): array
{
return [KernelEvents::REQUEST => ['onKernelRequest']];
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
if (0 !== stripos($event->getRequest()->getRequestUri(), '/user')) {
return;
}
if (!$this->storage instanceof NativeSessionStorage) {
return;
}
$options = ['cookie_path' => '/user'];
$this->storage->setOptions($options);
}
}
它在 Symfony 4.4 上运行良好,但是 Symfony 5.4 抛出服务 SessionStorageInterface 不存在且无法自动装配的异常。
除了创建我自己的 StorageFactory 之外,还有其他方法可以覆盖 SessionStorage 选项吗?
文档建议您改为注入 RequestStack