在应用程序初始化时,获取原则dbal为null


Getting doctrine dbal is null on app initialization

我使用身份验证成功处理程序在每次成功登录时填充会话中的一些值。我想做一些数据库操作,所以我从配置文件中传递@doctrine.dbal.default_connection。这是我的配置文件,我在其中覆盖success_handler函数。

services:     
    security.authentication.success_handler:
    class:  XYZ'UserBundle'Handler'AuthenticationSuccessHandler
    arguments:  ["@security.http_utils", {}, @doctrine.dbal.default_connection]
    tags:
        - { name: 'monolog.logger', channel: 'security' }

在AuthenticationSuccessHandler.php中,我的代码如下。。。

namespace Sourcen'UserBundle'Handler;
use Symfony'Component'HttpFoundation'JsonResponse;
use Symfony'Component'HttpFoundation'Response;
use Symfony'Component'HttpFoundation'Request;
use Symfony'Component'Security'Core'Authentication'Token'TokenInterface;
use Symfony'Component'Security'Http'Authentication'DefaultAuthenticationSuccessHandler;
use Symfony'Component'Security'Http'HttpUtils;
use Doctrine'DBAL'Connection;

class AuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler {
private $connection;
public function __construct( HttpUtils $httpUtils, array $options, Connection $dbalConnection ) {
    $this->connection = $dbalConnection;
    parent::__construct( $httpUtils, $options );
}
public function onAuthenticationSuccess( Request $request, TokenInterface $token ) {
    $response = parent::onAuthenticationSuccess( $request, $token );
    // DB CODE GOES  
    return $response;
}
}

当我直接执行一些控制器URL时,这是有效的。但当我执行我的应用程序主页url(如"www.xyz.com/web")时,它会抛出以下错误。。。

 Catchable fatal error: Argument 3 passed to XYZ'UserBundle'Handler'AuthenticationSuccessHandler::__construct() must be an instance of Doctrine'DBAL'Connection, none given, called in /opt/lampp/xyz/app/cache/prod/appProdProjectContainer.php on line 1006 and defined in /opt/lampp/xyz/src/Sourcen/UserBundle/Handler/AuthenticationSuccessHandler.php on line 18

知道怎么解决吗?

您不需要扩展DefaultAuthenticationSuccessHandler类。

尝试定义您的服务类别,如:

namespace XYZ'UserBundle'Handler;
use Symfony'Component'Security'Http'Event'InteractiveLoginEvent;
use Doctrine'DBAL'Connection;

class AuthenticationSuccessHandler  {
private $connection;
public function __construct( Connection $dbalConnection ) {
    $this->connection = $dbalConnection;
}
public function onAuthenticationSuccess( InteractiveLoginEvent $event ) {
    $user = $event->getAuthenticationToken()->getUser();
    // DB CODE GOES  
    return $response;
}
}

并配置标记到事件侦听器组件security.interactive_login 的服务

services:     
    security.authentication.success_handler:
    class:  XYZ'UserBundle'Handler'AuthenticationSuccessHandler
    arguments:  [@doctrine.dbal.default_connection]
    tags:
        - { name: 'kernel.event_listener', event: 'security.interactive_login'. method:'onAuthenticationSuccess' }

PS:你为什么不用doctrine.orm.entity_manager代替doctrine.dbal.default_connection呢?(在我的sf中,我没有将此服务转储到php app/console container:debug命令中)