簡體   English   中英

服務中的 Symfony 4 會話

[英]Symfony 4 session in service

我正在嘗試在我的自定義服務中使用會話變量。

我已經設置將以下行添加到 services.yaml

MySession:
    class: App\Services\SessionTest
    arguments: ['@session', '@service_container']

我的 SessionTest 看起來像這樣

namespace App\Services;

use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Request;

class SessionTest
{
    public $session;

    public function __construct()
    {

    }
    public function index()
    {
        echo "<pre>";
        var_dump($this->session);
        echo "</pre>";
    }
}

並收到此錯誤:Too few arguments to function App\Services\SessionTest::__construct(), 0 passed in /var/www/app.dev/src/Controller/OrdersController.php on line 33 and exactly 1 expected

您正在配置中使用構造函數注入,但看起來您正試圖在TestSession中接受屬性注入。

容器將使用大約如下代碼生成:

new SessionTest(SessionInterface $session, ContainterInterface $container)

因此,您要么需要更改TestSession以接受'@session''@service_container'作為構造函數參數:

protected $session;
protected $serviceContainer;

public function __construct(SessionInterface $session, ContainterInterface $serviceContainer)
{
    $this->sessions = $session;
    $this->serviceContainer = $container;
}

或者您需要將配置更改為如下所示:

MySession:
    class: App\Services\SessionTest
    properties:
        session: '@session'
        serviceContainer: '@service_container'

您還需要添加

   public $serviceContainer;

如果您想將服務容器作為屬性注入,則添加到TestSession

暫無
暫無

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

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