Call to a member function get() on null for FOSuserBundle - symfony

I am trying to do a redirect to the registration page, if a username does not exists in the user tables. I have done all the configurations needed and I have created the handler that looks like:
namespace UserBundle\Redirection;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
class AfterLoginFailureRedirection implements AuthenticationFailureHandlerInterface
{
/**
* #var \Symfony\Component\Routing\RouterInterface
*/
private $router;
/**
* #var \Symfony\Component\DependencyInjection\ContainerInterface
*/
private $container;
/**
* AfterLoginFailureRedirection constructor.
* #param RouterInterface $router
* #param ContainerInterface $container
*/
public function __construct(RouterInterface $router, ContainerInterface $container)
{
$this->router = $router;
}
/**
* #param Request $request
* #param AuthenticationException $token
* #return RedirectResponse
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
//$request = $this->container->get('request');
$token=$exception->getToken();
$username=$token->getUsername();
//$username = $request->request->get('email');
$user = $this->container->get('fos_user.user_manager')->findUserByUsername($username);
if(!$user->isUser()) {
$url=$this->container->get('router')->generate('fos_user_registration_register');
return new RedirectResponse($url);
}
}
}
For this part of the code I am getting the error:
$user = $this->container->get('fos_user.user_manager')->findUserByUsername($username);
Why is this happening?
Edit:
I initialized correcly constructor.
I inserted the code: else { $url=$this->container->get('router')->generate('fos_user_sec‌​urity_login'); return new RedirectResponse($url); } but it just redirects me without the login errors

Related

Symfony 4.4.2 - EventListener with TokenStorageInterface makes debug bar showing "An error occurred while loading the web debug toolbar."

I've just upgraded an app from Symfony 4.3.9 to 4.4.2. After that, I had the debug bar not working and showing "An error occurred while loading the web debug toolbar. "
After a long investigation, I found that it's because of an EventListener on security.authentication.failure event that was the cause.
Commenting the onAuthenticationFailure method content did nothing and after some investigation it works when removing the TokenStorageInterface from the tags and constructor... But I need it.
Any ideas?
Here's the code :
services.yaml
App\EventListener\LoginListener:
arguments: ["#doctrine", "#security.token_storage", "#router", "#event_dispatcher"]
tags:
- { name: kernel.event_listener, event: security.authentication.failure, method: onAuthenticationFailure }
LoginListener.php
<?php
namespace App\EventListener;
use App\Entity\AdminUser;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
/**
* Class LoginListener
* Listens to user log in events (failure, interactive log in) to provide additionnal security measures
*
* #package App\EventListener
*/
final class LoginListener
{
protected $doctrine;
protected $request;
protected $tokenStorage;
protected $router;
protected $dispatcher;
/**
* Login constructor.
*
* #param Registry $doctrine
* #param TokenStorageInterface $tokenStorage
* #param RouterInterface $router
* #param EventDispatcherInterface $dispatcher
*/
public function __construct(
Registry $doctrine,
TokenStorageInterface $tokenStorage,
RouterInterface $router,
EventDispatcherInterface $dispatcher
) {
$this->doctrine = $doctrine;
$this->tokenStorage = $tokenStorage;
$this->router = $router;
$this->dispatcher = $dispatcher;
}
/**
* #param AuthenticationFailureEvent $event
* #throws ORMException
* #throws OptimisticLockException
*/
public function onAuthenticationFailure(AuthenticationFailureEvent $event)
{
/** #var EntityManager $em */
$em = $this->doctrine->getManager();
$username = $event->getAuthenticationToken()->getUsername();
/** #var AdminUser $user */
$user = $em->getRepository(AdminUser::class)->findOneBy(['username' => $username]);
if ($user instanceof AdminUser) {
$user->addFailedLogin();
if ($user->getFailedLogin() == 5) {
$user->setLocked(1);
}
$em->persist($user);
$em->flush();
}
}
}
Thanks :)
---EDIT---
In fact that listener was an edit from another one. It doesn't need the TokenStorage but I'll have the problem in that one in a near future then :
<?php
namespace App\XXXBundle\EventListener;
use App\XXXBundle\Entity\AdminUser;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\ORM\EntityManager;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
/**
* Class Login
* Listens to user log in events (failure, interactive log in) to provide additionnal security measures
*
* #package App\XXXBundle\EventListener
*/
class Login
{
protected $doctrine;
protected $request;
protected $tokenStorage;
protected $router;
protected $dispatcher;
/**
* Login constructor.
*
* #param Registry $doctrine
* #param TokenStorage $tokenStorage
* #param RouterInterface $router
* #param EventDispatcherInterface $dispatcher
*/
public function __construct(
Registry $doctrine,
TokenStorage $tokenStorage,
RouterInterface $router,
EventDispatcherInterface $dispatcher
) {
$this->doctrine = $doctrine;
$this->tokenStorage = $tokenStorage;
$this->router = $router;
$this->dispatcher = $dispatcher;
}
/**
* #param AuthenticationFailureEvent $event
* #throws \Doctrine\ORM\ORMException
* #throws \Doctrine\ORM\OptimisticLockException
*/
public function onAuthenticationFailure(AuthenticationFailureEvent $event)
{
/** #var EntityManager $em */
$em = $this->doctrine->getManager();
$userName = $event->getAuthenticationToken()->getUsername();
/** #var AdminUser $user */
$user = $em->getRepository(AdminUser::class)->findOneByUsername($userName);
if ($user instanceof AdvancedUserInterface) {
$user->addFailedLogin();
if ($user->getFailedLogin() == 5) {
$user->setLocked(1);
}
$em->persist($user);
$em->flush();
}
}
/**
* #param InteractiveLoginEvent $event
* #throws \Exception
*/
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof AdvancedUserInterface) {
$em = $this->doctrine->getManager();
if ($user->getLocked()) {
$this->tokenStorage->setToken(null);
throw new CustomUserMessageAuthenticationException('Compte verrouillé.');
}
if ($user->getExpiresAt() && $user->getExpiresAt() <= new \DateTime()) {
$user->setIsActive(0);
$em->persist($user);
$em->flush();
$this->tokenStorage->setToken(null);
throw new CustomUserMessageAuthenticationException('Compte expiré.');
}
if ($user->getCredentialsExpireAt() && $user->getCredentialsExpireAt() <= new \DateTime()) {
$this->dispatcher->addListener(KernelEvents::RESPONSE, [$this, 'redirectToCredentialsChange']);
}
$user->setLastLogin(new \DateTime());
$user->setFailedLogin(0);
$em->persist($user);
$em->flush();
}
}
public function redirectToCredentialsChange(ResponseEvent $event)
{
$event->getResponse()->headers->set('Location', $this->router->generate('admin_security_changecredentials'));
}
}

Unable to login via PHPUnit Tests with Symfony 4

I'm trying to run a simple auth test using PHPUnit with Symfony 4 to see if the user has successfully logged in. I followed the documentation for running a auth test. The /admin page will automatically redirect to /login if the user is not signed in.
I'm getting the this error on running the test:
There was 1 failure:
1) App\Tests\AuthTest::testAdminPanel
Failed asserting that 302 is identical to 200.
~config/packages/test/security.yaml:
security:
firewalls:
main:
http_basic: ~
Test:
public function testAdminPanel() {
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'username',
'PHP_AUTH_PW' => 'password',
));
$crawler = $client->request('GET', '/admin');
$this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode());
}
Note: The username account along with the password, password, do exist in the database.
Security Controller:
<?php
namespace App\Security;
use App\Form\LoginFormType;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
/**
* Class LoginFormAuthenticator
* #package App\Security
*/
class LoginFormAuthenticator extends AbstractGuardAuthenticator
{
/**
* #var FormFactoryInterface
*/
private $formFactory;
/**
* #var EntityManager
*/
private $em;
/**
* #var RouterInterface
*/
private $router;
/**
* #var UserPasswordEncoder
*/
private $userPasswordEncoder;
/**
* LoginFormAuthenticator constructor.
* #param FormFactoryInterface $formFactory
* #param EntityManagerInterface $em
* #param RouterInterface $router
* #param UserPasswordEncoderInterface $userPasswordEncoder
*/
public function __construct(FormFactoryInterface $formFactory, EntityManagerInterface $em, RouterInterface $router, UserPasswordEncoderInterface $userPasswordEncoder)
{
$this->formFactory = $formFactory;
$this->em = $em;
$this->router = $router;
$this->userPasswordEncoder = $userPasswordEncoder;
}
/**
* #return string
*/
protected function getLoginUrl()
{
return $this->router->generate('login');
}
/**
* #param Request $request
* #return bool
*
* Called on every request to decide if this authenticator should be
* used for the request. Returning false will cause this authenticator
* to be skipped. Current implementation checks that this request method is POST and
* that the user is on the login page.
*
*/
public function supports(Request $request)
{
return ($request->attributes->get('_route') === 'login' && $request->isMethod('POST'));
}
/**
* #param Request $request
* #param AuthenticationException|null $authException
* #return RedirectResponse|Response
*/
public function start(Request $request, AuthenticationException $authException = null)
{
return new RedirectResponse($this->router->generate('login'));
}
/**
* #param Request $request
* #return bool|mixed
*/
public function getCredentials(Request $request)
{
$form = $this->formFactory->create(LoginFormType::class);
$form->handleRequest($request);
$data = $form->getData();
$request->getSession()->set(
Security::LAST_USERNAME,
$data['username']
);
return $data;
}
/**
* #param mixed $credentials
* #param UserProviderInterface $userProvider
* #return null|object|UserInterface
*/
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = $credentials['username'];
$user = $this->em->getRepository('App:User')->findOneBy(['username' => $username]);
if(empty($user)) {
$user = $this->em->getRepository('App:User')->findOneBy(array('email' => $username));
}
return $user;
}
/**
* #param mixed $credentials
* #param UserInterface $user
* #return bool
*/
public function checkCredentials($credentials, UserInterface $user)
{
$password = $credentials['password'];
if($this->userPasswordEncoder->isPasswordValid($user, $password)) {
return true;
}
return false;
}
/**
* #return string
*/
public function getDefaultSuccessRedirectUrl()
{
return $this->router->generate('default');
}
/**
* #param Request $request
* #param AuthenticationException $exception
* #return RedirectResponse
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
return new RedirectResponse($this->router->generate('login'));
}
/**
* #param Request $request
* #param TokenInterface $token
* #param string $providerKey
* #return null|RedirectResponse|Response
* #throws \Doctrine\ORM\ORMException
* #throws \Doctrine\ORM\OptimisticLockException
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$user = $token->getUser();
$user->setLastLogin(new \DateTime('now'));
$this->em->persist($user);
$this->em->flush();
return new RedirectResponse($this->router->generate('easyadmin'));
}
/**
* #return bool
*/
public function supportsRememberMe()
{
return false;
}
}
You are using AbstractGuardAuthenticator class to authenticate your users. Following the link you provided, you have to use PostAuthenticationGuardToken class.
public function testAdminPanel(): void
{
// Create client
$client = static::createClient();
// Get user
$user = ...; // The user entity
// Login the user
$this->simulateLogin($user);
// Perform request
$crawler = $client->request('GET', '/admin');
// Assert
$this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode());
}
private function simulateLogin(User $user): void
{
// Get session
$session = self::$container->get('session');
// Set firewall
$firewall = '...'; // Your firewall name
// Authenticate the user
$token = new PostAuthenticationGuardToken($user, $firewall, $user->getRoles());
$session->set('_security_' . $firewall, serialize($token));
$session->save();
// Set cookie
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);
}
To be able to use this method, you can create a fixture to create the user in your test database. See Doctrine Fixture Bundle and even use Liip Test Fixture Bundle to be able to load the fixture and truncate the database at each functional test.
I am using Symfony 5, but I guess it will not be very different.
Hope it will help !
your test seems fine. HTTP 302 means redirect, we are usually redirected after a successfull login.
try to add $client->followRedirects();
as suggested at https://symfony.com/doc/current/testing#redirecting

Authentication Failure Handler did not return a Response

I have extended the DefaultAuthenticationFailureHandler in order to redirect users to register page if the username is not in the database. it works fine for the first part.
If the username exists in the database I want from the Controller the default behavior i.e. to redirect to the login page with the login error message. Why it is not issuing a redirect?
namespace UserBundle\Redirection;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;
use UserBundle\Controller\SecurityController;
class AfterLoginFailureRedirection extends DefaultAuthenticationFailureHandler
{
/**
* #var \Symfony\Component\Routing\RouterInterface
*/
private $router;
/**
* #var \Symfony\Component\DependencyInjection\ContainerInterface
*/
private $container;
public function setRouter(RouterInterface $router)
{
$this->router = $router;
}
public function setContainer(ContainerInterface $container)
{
$this->container=$container;
}
/**
* #param Request $request
* #param AuthenticationException $token
* #return RedirectResponse
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
//$request = $this->container->get('request');
$token=$exception->getToken();
$username=$token->getUsername();
//$username = $request->request->get('email');
$user = $this->container->get('fos_user.user_manager')->findUserByUsername($username);
if(!$user) {
$url=$this->container->get('router')->generate('fos_user_registration_register');
return new RedirectResponse($url);
}
else
{
parent::onAuthenticationFailure($request,$exception);
}
}}
You don't return anything in your else case
correct code should be :
else {
return parent::onAuthenticationFailure($request,$exception);
}

Testing PHPSpec symfony logged user

I'am new in testing PHP with PHPSpec. I have a class where i inject symfony current logged user (TokenStorageInterface). And make changes with that user.
<?php
namespace AppBundle\Service;
use AppBundle\Entity\Payment;
use AppBundle\Entity\User;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class TransferService
{
/**
* #var EntityManager
*/
private $entityManager;
/**
* #var TokenStorageInterface
*/
private $tokenStorage;
/**
* #var User
*/
private $currentUser;
/**
* #var InvoiceService
*/
private $invoiceService;
/**
* PaymentManager constructor.
* #param EntityManager $entityManager
* #param TokenStorageInterface $tokenStorage
* #param InvoiceService $invoiceService
*/
public function __construct(
EntityManager $entityManager,
TokenStorageInterface $tokenStorage,
InvoiceService $invoiceService
) {
$this->entityManager = $entityManager;
if ($tokenStorage->getToken() === null) {
throw new \Exception('User not logged in');
}
$this->currentUser = $tokenStorage->getToken()->getUser();
$this->invoiceService = $invoiceService;
}
/**
* #param Payment $payment
*/
public function transfer(Payment $payment)
{
$payer = $this->currentUser;
$amount = $payment->getAmount();
$receiver = $payment->getReceiver();
if ($payer === $receiver) {
throw new \LogicException('Cannot be same User');
}
if ($payer->getBalance() < $amount) {
throw new \LogicException('Not enough in balance');
}
$payment->setPayer($payer);
//TODO: Move to class?
$this->subtractBalance($payer, $amount);
$this->addBalance($receiver, $amount);
$this->invoiceService->createInvoice($payment);
$this->entityManager->persist($payment);
$this->entityManager->flush();
}
/**
* #param User $user
* #param $amount
*/
private function subtractBalance(User $user, $amount)
{
$user->setBalance($user->getBalance() - $amount);
}
/**
* #param User $user
* #param $amount
*/
private function addBalance(User $user, $amount)
{
$temp = $user->getBalance();
$user->setBalance($user->getBalance() + $amount);
}
}
And have wrote Spec for that class:
<?php
namespace spec\AppBundle\Service;
use AppBundle\Entity\Payment;
use AppBundle\Entity\User;
use AppBundle\Service\InvoiceService;
use Doctrine\ORM\EntityManager;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class TransferServiceSpec extends ObjectBehavior
{
function let(EntityManager $entityManager, TokenStorage $tokenStorage, InvoiceService $invoiceService)
{
$user = new User();
$user->setUsername('aaa');
$user->setBalance(100.10);
$temp = new UsernamePasswordToken($user, null, 'main', ['ROLE_USER']);
$tokenStorage->getToken()->willReturn($temp);
$this->beConstructedWith($entityManager, $tokenStorage, $invoiceService);
}
function it_is_initializable()
{
$this->shouldHaveType('AppBundle\Service\TransferService');
}
function it_should_transfer_money(
User $user,
EntityManager $entityManager,
TokenStorageInterface $tokenStorage,
InvoiceService $invoiceService,
Payment $payment
) {
$user->getBalance()->willReturn(0);
$user->setBalance(99.9)->shouldBeCalled();
$payment->getReceiver()->willReturn($user);
//TODO how to check injected current user?
//$payment->getPayer()->willReturn($tokenStorage->getToken());
$payment->getAmount()->willReturn(99.9);
$invoiceService->createInvoice($payment)->shouldBeCalled();
$entityManager->persist($payment)->shouldBeCalled();
$entityManager->flush()->shouldBeCalled();
$this->transfer($payment);
}
}
The problem is, how to check that changes were made (to test that balance was edited) in current user (injected token storage getUser()) because following method dont work:
$payment->getPayer()->willReturn($tokenStorage->getToken()->getUser());
Call to undefined method Prophecy\Prophecy\MethodProphecy::getUser()
You should not call methods on prophecy, but mock everything instead, see:
function it_should_transfer_money(
User $user,
EntityManager $entityManager,
TokenStorageInterface $tokenStorage,
TokenInterface $token,
UserInterface $user,
InvoiceService $invoiceService,
Payment $payment
) {
$user->getBalance()->willReturn(0);
$user->setBalance(99.9)->shouldBeCalled();
$payment->getReceiver()->willReturn($user);
$tokenStorage->getToken()->willReturn($token);
$token->getUser()->willReturn($user);
$payment->getPayer()->willReturn($user);
$payment->getAmount()->willReturn(99.9);
$invoiceService->createInvoice($payment)->shouldBeCalled();
$entityManager->persist($payment)->shouldBeCalled();
$entityManager->flush()->shouldBeCalled();
$this->transfer($payment);
}

How to resolve a error in EventListener?

I have a problem in redirect path according to role in FOSuserBndle.The problem is in :
FatalErrorException: Error: Call to a member function generate() on a
non-object in.....
This is the event listener
namespace Register\UserBundle\EventListener;
///////////////////////////////
//////////////////////////////
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine; // for Symfony 2.1.0+
// use Symfony\Bundle\DoctrineBundle\Registry as Doctrine; // for Symfony 2.0.x
/**
* Custom login listener.
*/
class LoginListener
{
protected $router;
/** #var \Symfony\Component\Security\Core\SecurityContext */
private $securityContext;
/** #var \Doctrine\ORM\EntityManager */
private $em;
/**
* Constructor
*
* #param SecurityContext $securityContext
* #param Doctrine $doctrine
*/
public function __construct( SecurityContext $securityContext, Doctrine $doctrine )
{
$this->securityContext = $securityContext;
$this->em = $doctrine->getEntityManager();
}
/**
* Do the magic.
*
* #param InteractiveLoginEvent $event
*/
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
if ($this->securityContext->isGranted('ROLE_PATIENT')) {
$response = new RedirectResponse($this->router->generate('demands'));
//this->redirect($this->generateUrl('home'));
}
if ($this->securityContext->isGranted('ROLE_THERAPIST')) {
// user has logged in using remember_me cookie
print_r("FFFFFFFFFFFFFTHERAPIST");
die;
}
// do some other magic here
$user = $event->getAuthenticationToken()->getUser();
$type = $user->getType()->getId();
print_r( $type);
die;
// ...
}
}
It seems that the router is not injected in your listener/service.
Listener class :
...
use Symfony\Component\Routing\Router;
class LoginListener
{
protected $container;
protected $em;
protected $router;
public function __construct(ContainerInterface $container, EntityManager $em, Router $router)
{
$this->container = $container;
$this->em = $em;
$this->router = $router;
}
...
}
Service declaration :
my_bundle.my_listener:
class: %my_bundle.my_listener.class%
arguments: [ #service_container, #doctrine.orm.entity_manager, #router ]

Resources