我已经在这个类的构造方法中定义了 Request 。
/**
* @var Request
*/
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试在这样的函数中检索帖子数据时:
public function postListsAction()
{
dd($this->request->get("title"));
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
无法自动装配服务“App\Controller\ListController”:方法“__construct()”的参数“$request”引用类“Symfony\Component\HttpFoundation\Request”,但不存在这样的服务。
我该如何解决这个问题?
正如错误消息所说,您尝试注入的请求类未声明为服务。使用 RequestStack 代替:
namespace App\Newsletter;
use Symfony\Component\HttpFoundation\RequestStack;
class NewsletterManager
{
protected $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function anyMethod()
{
$request = $this->requestStack->getCurrentRequest();
// ... do something with the request
}
}
Run Code Online (Sandbox Code Playgroud)
问候