Symfony 3.3升级至3.4的BC兼容问题:自定义SwitchUserListener报错
I’ve dealt with this exact compatibility snag during Symfony upgrades before, so let me break down how to fix it quickly.
The core problem here is that Symfony 3.4 introduced a backwards-incompatible change to the base SwitchUserListener class: its constructor was updated to include two new optional dependencies—LoggerInterface and EventDispatcherInterface. Since you’ve fully overridden this class in your legacy code, your custom implementation’s constructor no longer matches the base class signature, which triggers the cache-clear exception.
Here’s the step-by-step solution:
Update your custom SwitchUserListener constructor to match the 3.4 base class’s parameter list. Here’s what the adjusted constructor should look like:
use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Security\Http\Firewall\SwitchUserListener as BaseSwitchUserListener; class SwitchUserListener extends BaseSwitchUserListener { public function __construct( \Symfony\Component\Security\Core\SecurityContextInterface $securityContext, \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface $tokenStorage, \Symfony\Component\Security\Core\User\UserProviderInterface $provider, string $usernameParameter, \Symfony\Component\Security\Core\User\UserCheckerInterface $userChecker, string $firewallName, LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null ) { // Pass all parameters to the parent constructor first parent::__construct( $securityContext, $tokenStorage, $provider, $usernameParameter, $userChecker, $firewallName, $logger, $dispatcher ); // Your custom override logic goes here } // Rest of your custom methods... }Adjust your service configuration (if defining the listener manually):
If you have an explicit service definition for your custom listener inservices.ymlor similar, ensure you add the new optional parameters. You can inject them explicitly or let Symfony’s auto-wiring handle them (if enabled in 3.4):services: app.switch_user_listener: class: App\Security\Firewall\SwitchUserListener arguments: - '@security.context' - '@security.token_storage' - '@your_user_provider' - '_switch_user' - '@security.user_checker' - 'main' # Replace with your actual firewall name - '@logger' # Optional, omit to use null - '@event_dispatcher' # Optional, omit to use null tags: - { name: kernel.event_listener, event: kernel.request, priority: 10 }Optional: Prep for future upgrades
Note thatSecurityContextInterfaceis marked as deprecated in Symfony 3.4. For a smoother transition to Symfony 4.x later, you can start migrating toTokenStorageInterfaceandAuthorizationCheckerInterfaceinstead, but this isn’t required for the immediate 3.3→3.4 fix.
Once you’ve applied these changes, run php bin/console cache:clear again—the exception should be resolved.
内容的提问来源于stack exchange,提问作者Guillaume T.

