繁体   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