【问题标题】:Symfony 4 session in serviceSymfony 4 会话服务中
【发布时间】:2018-12-10 19:00:32
【问题描述】:

我正在尝试在我的自定义服务中使用会话变量。

我已经设置将以下行添加到 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>";
    }
}

并收到此错误: 函数 App\Services\SessionTest::__construct() 的参数太少,在第 33 行的 /var/www/app.dev/src/Controller/OrdersController.php 中传递了 0,而预期正好是 1

【问题讨论】:

  • 从错误消息看来,您似乎正在尝试 new SessionTest();来自 OrdersController?此外,您发布的 __construct 并不表示正在注入 SessionInterface。
  • 我已经尝试过使用 SessionInterface 并收到相同的错误消息
  • 非常值得怀疑。但是你看到我评论的第一部分了吗?您是尝试新的 SessionTest 还是尝试将其注入控制器?
  • 是的,我正在尝试执行新的 SessionTest 如果我使用您的版本,则收到 NULL
  • 好的。 php new 操作符对 Symfony 的服务容器一无所知。查看文档以了解如何将 SessionTest 等服务注入控制器。 symfony.com/doc/current/…

标签: php symfony session constructor


【解决方案1】:

您正在配置中使用构造函数注入,但看起来您正试图接受 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-15
    • 2019-06-01
    • 2019-06-24
    • 2019-02-21
    • 2020-03-21
    • 2018-12-24
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多