我收到此错误:Notice: Undefined property: MyApp\AuthBundle\Other\AuthenticationSuccessHandler::$httpUtils
在我的登录成功处理程序中使用此代码的结果是:
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
return $this->httpUtils->createRedirectResponse($request, $this->determineTargetUrl($request));
}
我意识到这是因为我的课堂上没有httpUtils属性。但是,我不知道如何注射它?
目前我只在构造函数中使用了RouterInterface $ router和EntityManager $ em。我需要添加更多参数吗?或者更新任何YML文件?
答案 0 :(得分:3)
您需要更改构造函数以接受security.http_utils
服务:
class LoginSuccessHandler ...
{
protected $httpUtils;
...
public function __construct(HttpUtils $httpUtils, ...)
{
$this->httpUtils = $httpUtils;
$this->router = $router;
$this->security = $security;
}
然后更新您的服务:
login_success_handler:
class: AppBundle\EventListener\LoginSuccessHandler
arguments: ["@security.http_utils", ... ]
tags:
- { name: 'monolog.logger', channel: 'security' }
我还建议您延长DefaultAuthenticationSuccessHandler
这将为您提供determineTargetUrl
方法:
class LoginSuccessHandler extends DefaultAuthenticationSuccessHandler
{
public function __construct(HttpUtils $httpUtils, ...)
{
parent::__construct($httpUtils);
$this->router = $router;
$this->security = $security;
}
// ...
} 或者你可以把它复制到你的班级:
/**
* Builds the target URL according to the defined options.
*
* @param Request $request
*
* @return string
*/
protected function determineTargetUrl(Request $request)
{
if ($this->options['always_use_default_target_path']) {
return $this->options['default_target_path'];
}
if ($targetUrl = $request->get($this->options['target_path_parameter'], null, true)) {
return $targetUrl;
}
if (null !== $this->providerKey && $targetUrl = $request->getSession()->get('_security.'.$this->providerKey.'.target_path')) {
$request->getSession()->remove('_security.'.$this->providerKey.'.target_path');
return $targetUrl;
}
if ($this->options['use_referer'] && ($targetUrl = $request->headers->get('Referer')) && $targetUrl !== $this->httpUtils->generateUri($request, $this->options['login_path'])) {
return $targetUrl;
}
return $this->options['default_target_path'];
}
顺便说一句。如果您想知道http_utils服务在哪里是私有的:
$ php app/console container:debug --show-private | grep security.http_utils