简体   繁体   English

服务中的 Symfony 4 会话

[英]Symfony 4 session in service

I'm trying to use session variables in my custom service.我正在尝试在我的自定义服务中使用会话变量。

I already set add the following lines to services.yaml我已经设置将以下行添加到 services.yaml

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

And my SessionTest looks like this我的 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>";
    }
}

And receive this error: 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并收到此错误: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

You are using constructor injection in your config, but it looks like you're trying to accept property injection in TestSession .您正在配置中使用构造函数注入,但看起来您正试图在TestSession中接受属性注入。

The container will be generated with code like approximately this:容器将使用大约如下代码生成:

new SessionTest(SessionInterface $session, ContainterInterface $container)

So you either need to change TestSession to accept '@session' and '@service_container' as constructor arguments:因此,您要么需要更改TestSession以接受'@session''@service_container'作为构造函数参数:

protected $session;
protected $serviceContainer;

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

Or you need to change your config to something like this:或者您需要将配置更改为如下所示:

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

You will also need to add您还需要添加

   public $serviceContainer;

to TestSession if you want to inject the service container as a property.如果您想将服务容器作为属性注入,则添加到TestSession

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM