我正在尝试在自定义服务中使用会话变量。
我已经设置将以下行添加到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
答案 0 :(得分:0)
您正在配置中使用构造函数注入,但是您似乎正在尝试在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
。