【发布时间】:2017-06-23 18:13:19
【问题描述】:
我在这里阅读了有关会话的信息:
https://symfony.com/doc/current/components/http_foundation/sessions.html
如果我直接使用代码,使用 Guard 的 Symfony 登录在第一次尝试时不起作用(第一次总是失败,第二次成功)。所以我猜我必须使用$this->container->get('session') 的会话。但是添加袋子让我感到困惑。
我试过了:
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request) {
$session=$this->container->get('session');
$cart=new AttributeBag('ShoppingCartItems');
$session->registerBag($cart);
$session->start();
...但它告诉我
会话已开始时无法注册包。
我试过了:
...在捆绑包中:
public function build(ContainerBuilder $container) {
parent::build($container);
$container->addCompilerPass(new \Website\DependencyInjection\Compiler\InjectShoppingCart());
}
...然后是InjectShoppingCart
namespace Website\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
class InjectShoppingCart implements CompilerPassInterface {
public function process(ContainerBuilder $container) {
$bagDefinition = new Definition();
$bagDefinition->setClass(AttributeBag::class);
$bagDefinition->addArgument("ShoppingCartItems");
$bagDefinition->addMethodCall("setName", ["ShoppingCartItems"]);
$container->setDefinition("ShoppingCartItemsService",$bagDefinition);
$container->getDefinition("session")->addMethodCall("registerBag",[new Reference("ShoppingCartItemsService")]);
}
}
...我尝试使用的 Cargo Cult 风格,来自 question 44723613。不管它做什么,它都不会导致注册一个属性包。
到目前为止,无论我尝试了什么,Guard 身份验证都会中断,否则包没有注册。不过,我希望两者都做,希望不安装外部库的 Megs 和 Megs。
不可能这么难。我错过了什么?
【问题讨论】:
标签: symfony session symfony-3.2