Php 在Symfony 3控制器中获取请求和会话

Php 在Symfony 3控制器中获取请求和会话,php,symfony,Php,Symfony,我有个大问题,请帮帮我。因此,我想创建一个登录系统,该系统将只使用以下用户: providers: in_memory: memory: users: 所以我的全局路由:/app/config/routing.yml: app_admin: resource: "@AppAdminBundle/Resources/config/routing.yml" prefix: /admin AdminBundle中的我的路由: app_admi

我有个大问题,请帮帮我。因此,我想创建一个登录系统,该系统将只使用以下用户:

providers:
  in_memory:
      memory:
          users:
所以我的全局路由:
/app/config/routing.yml

app_admin:
    resource: "@AppAdminBundle/Resources/config/routing.yml"
    prefix:   /admin
AdminBundle中的我的路由:

app_admin_homepage:
    path:     /
    defaults: { _controller: AppAdminBundle:Login:index }
login:
    path:   /login
    defaults:  { _controller: AppAdminBundle:Login:login }
login_check:
    path:   /login_check
我的登录控制器:

<?php

namespace App\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;

class LoginController extends Controller
{
public function indexAction()
{
    return $this->render('AppAdminBundle:Member:login.html.twig');
}
public function loginAction()
{
    $request = $this->get('request');
    $session = $this->get('session');

    if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
        $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
    } else {
        $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
        $session->remove(SecurityContext::AUTHENTICATION_ERROR);
    }

    return $this->render('AppAdminBundle:Member:login.html.twig', array(
        'last_username' => $session->get(SecurityContext::LAST_USERNAME),
        'error'         => $error,
    ));
}
}
当我尝试访问时:
/admin/login

我收到以下错误:
您请求了一个不存在的服务“请求”。你是说其中一个:“路由器.请求上下文”,“请求栈”,“独白.记录器.请求”,“数据采集器.请求”?


你能帮帮我吗?提前感谢并为我的英语道歉

这是因为您试图在控制器中获得一项不存在的服务。在symfony控制器中,您可以在方法调用中获取请求:

在Logincontroller中,添加以下use语句:

use Symfony\Component\HttpFoundation\Request;
在你的函数声明中

public function loginAction(Request $request)
{
    // you can directly use $request
    ....
}
现在,您可以删除尝试获取不存在服务的行:

// remove this line
$request = $this->get('request');
另外,我不确定您是否会使用get(“session”)来获取会话。根据Symfony的文档,您应该执行以下操作:

$session = $request->getSession();

参见

这正是@jiboulex所说的,补充了它:

这是由于内部使用
$this('request')
$this->getRequest()
被弃用所致。 如果您查看迁移指南,它将明确执行此更改:

关于会话,您可以通过文档中的
$this->getSession()
获得它: 而不是这个

$this->get('request')
使用


是否删除了带有$request=$this->get('request');的行?symfony3中是否存在SecurityContext的另一种替代方案?是的,但请阅读文档。这一切都已经解释清楚了,如果你只是想摆脱它,你会不断遇到一个又一个的绊脚石。确保你只看Symfony 3的东西。它和Symfony 2之间有很多变化。不要忘记投票并选择正确的答案,这将帮助其他正在寻找这个问题的人!
$session = $request->getSession();
$this->get('request')
$this->get('request_stack')->getCurrentRequest()