如何在symfony中调用redirectToRoute方法接受控制器

时间:2017-12-14 06:49:20

标签: php symfony symfony-forms

我是symfony的新手,我在系统中任何用户登录后都会做一些流程,为此提供一个服务,代码如下:

security.authentication.success_handler:
        class:   AppBundle\Handler\AuthenticationSuccessHandler
        arguments:  ["@security.http_utils", {}]
        tags:
            - { name: 'monolog.logger', channel: 'security' }

在安全文件中添加一行,代码如下:

success_handler: security.authentication.success_handler

在文件夹处理程序中创建一个新的AuthenticationSuccessHandler文件,代码如下:

<?php

namespace AppBundle\Handler;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\HttpFoundation\Response;


class AuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler {

    public function __construct(HttpUtils $httpUtils, array $options ) {

        parent::__construct( $httpUtils,$options);
    }

    public function onAuthenticationSuccess( Request $request, TokenInterface $token ) {
        $user=$token->getUser();
        if (!empty($user) && $user->hasRole('ROLE_MEDICAL_PROVIDER')) {
            if($user->getMedicalProvider()->getIsRegistrationCompleted() != 1) {
                if($user->getMedicalProvider()->getRequestAssistance() == 1) {


                    return $this->redirectToRoute('registration_medical_provider_step'.$user->getMedicalProvider()->getRequestAssistanceStep());


                } else {
                    return $this->httpUtils->createRedirectResponse($request, $this->determineTargetUrl($request));
                }
            } else {
                return $this->httpUtils->createRedirectResponse($request, $this->determineTargetUrl($request));    
            }

        }
        else {
            return $this->httpUtils->createRedirectResponse($request, $this->determineTargetUrl($request));    
        }

    }
}

我希望在登录后重定向到另一条路线,基于上面代码i用户的条件,它给我下面的错误:

  

错误:调用未定义的方法redirectToRoute()   AuthenticationSuccessHandler.php文件

我如何从symfony中的登录验证成功处理程序文件调用方法?

2 个答案:

答案 0 :(得分:2)

你不在控制器中,所以你可以试试像:

return $this->httpUtils->createRedirectResponse($request, 'registration_medical_provider_step'.$user->getMedicalProvider()->getRequestAssistanceStep());

答案 1 :(得分:0)

您正在扩展DefaultAuthenticationSuccessHandler,因此 redirectToRoute() 方法在这个类中不存在。

然而,你可以尝试这个

$this->httpUtils->generateUri($request, 'your_target_path');

了解更多HttpUtils 并看到这种方法 generateUri(Request $request, string $path)