我有symfony2申请表。我想在用户登录到存储在数据库中的最后登录语言环境时设置语言环境。
这里是services.yml:
login_listener:
class: AppBundle\EventListener\AuthListener
arguments:
- @request_stack
- @users_manager
- @session
tags:
- { name: kernel.event_subscriber }
这里是authListener.php:
<?php
namespace AppBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\HttpFoundation\RequestStack;
use AppBundle\Doctrine\DBAL\DBALManager;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\HttpFoundation\Session\Session;
class AuthListener implements EventSubscriberInterface
{
protected $requestStack;
protected $usersManager;
protected $session;
public function __construct(RequestStack $requestStack, DBALManager $usersManager, Session $session)
{
$this->requestStack = $requestStack;
$this->usersManager = $usersManager;
$this->session = $session;
}
public static function getSubscribedEvents()
{
return [
AuthenticationEvents::AUTHENTICATION_SUCCESS => 'onAuthenticationSuccess',
];
}
public function onAuthenticationSuccess($event)
{
// even empty function cause error
// here i get locale from db and set to session
}
}
即使我将onAuthenticationSuccess留空,也会得到[get]/\uWDT/f3a2ee404notfound error。仅在/login页上发生错误。
最佳答案
这对我来说在symfony 2.7上很有用
namespace Acme\YourBundle\Listeners;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
class AuthenticationListener implements EventSubscriberInterface
{
public function onAuthenticationSuccess(AuthenticationEvent $event) {
if(!$event->getAuthenticationToken() instanceof AnonymousToken) {
// Apply action only when the user is actually authenticated and not a guest.
// If the user is authenticated, the token will be `UsernamePasswordToken`.
}
}
public static function getSubscribedEvents() {
return array(
AuthenticationEvents::AUTHENTICATION_SUCCESS => 'onAuthenticationSuccess'
);
}
}
在
services.yml
中:acme.security.authentication_event_listener:
class: Acme\YourBundle\Listeners\AuthenticationListener
tags:
- { name: kernel.event_subscriber, event: security.authentication.success, method: onAuthenticationSuccess }