簡體   English   中英

如何向 symfony 會話添加額外的包

[英]How to add extra bag to symfony session

我想在 symfony 會話中添加一個額外的包。

我在編譯器傳遞中這樣做:

public function process(ContainerBuilder $container)
{   
    $bag = new AttributeBag("my_session_attributes");

    $container->getDefinition("session")
        ->addMethodCall("registerBag", [$bag]);
}

但我收到一條消息異常:

如果參數是對象或資源,則無法轉儲服務容器。

這是跟蹤堆棧:

  1. 在 XmlDumper.php 第 379 行
  2. 在 XmlDumper.php 第 328 行中的 XmlDumper::phpToXml(object(AttributeBag))
  3. 在 XmlDumper->convertParameters(array(object(AttributeBag)), 'argument', object(DOMElement)) 在 XmlDumper.php 第 94 行
  4. 在 XmlDumper->addMethodCalls(array(array('registerBag', array(object(AttributeBag)))), object(DOMElement)) 在 XmlDumper.php 第 183 行
  5. 在 XmlDumper->addService(object(Definition), 'session', object(DOMElement)) 在 XmlDumper.php 第 272 行
  6. 在 XmlDumper.php 第 52 行中的 XmlDumper->addServices(object(DOMElement))
  7. 在 ContainerBuilderDebugDumpPass.php 第 34 行中的 XmlDumper->dump()
  8. 在 ContainerBuilderDebugDumpPass->process(object(ContainerBuilder)) 在 Compiler.php 第 104 行
  9. 在 Compiler->compile(object(ContainerBuilder)) 在 ContainerBuilder.php 第 598 行
  10. 在 ContainerBuilder->compile() 在 Kernel.php 第 514 行
  11. 在 Kernel->initializeContainer() 在 Kernel.php 第 133 行
  12. 在 Kernel->boot() 在 Kernel.php 第 182 行
  13. 在內核->句柄(對象(請求))在 app_dev.php 第 29 行

如果我不能在服務定義中傳遞對象參數,我應該如何添加新包?

好的,在發布問題后,我有一個想法,我認為這是一種解決方法,但它有效。

AttributeBag 也必須注冊為服務:

public function process(ContainerBuilder $container)
{   
    $bagDefinition = new Definition();
    $bagDefinition->setClass(AttributeBag::class);
    $bagDefinition->addArgument("my_session_attributes");
    $bagDefinition->addMethodCall("setName", ["my_session_attributes"]);
    $bagDefinition->setPublic(false);
    $container->setDefinition("my_session_attributes_service", $bagDefinition);

    $container->getDefinition("session")
        ->addMethodCall("registerBag", [new Reference("my_session_attributes_service")]);
}

這個問題在文檔中不清楚,你的例子有點幫助,但我認為有一種更干凈的方法來向 symfony 會話添加一個包,這就是我所做的(symfony 4+)

添加一個包類,例如你可以擴展 AttributeBag 一個

namespace App\Tracking;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;    

class TrackingBag extends AttributeBag
{
    public function __construct(string $storageKey = 'trackings')
    {
        parent::__construct($storageKey);
        $this->setName($storageKey);
    }
}

然后添加一個CompilerPass

public function process(ContainerBuilder $container)
{
    $container->getDefinition("session")->addMethodCall(
        "registerBag",
        [new Reference('App\\Tracking\\TrackingBag')]
    );
}

然后你可以像在樹枝上那樣使用它

{{ app.session.bag('trackings').all }}

我仍然相信有更清潔的方法,但這是唯一對我有用的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM