I am using FOSUserBundle in my Symfony 2.3 project, and I want to execute some code right after the user confirms his account clicking on the email link. I was trying to override the
class RegistrationController extends ContainerAware
{
...
}
but no luck :(
Can I create any kind of Event to be executed right after this action?
Thanks!
You can create an EventListener which listens for FOSUserEvents::REGISTRATION_CONFIRMED like this:
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\UserEvent;
class RegistrationConfirmedEventListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(FOSUserEvents::REGISTRATION_CONFIRMED => 'performOnRegistrationConfirmed');
}
public function performOnRegistrationConfirmed(UserEvent $event)
{
$user = $event->getUser();
// Do something
}
}
Related
As my IDE points out, the AbstractController::getDoctrine() method is now deprecated.
I haven't found any reference for this deprecation neither in the official documentation nor in the Github changelog.
What is the new alternative or workaround for this shortcut?
As mentioned here:
Instead of using those shortcuts, inject the related services in the constructor or the controller methods.
You need to use dependency injection.
For a given controller, simply inject ManagerRegistry on the controller's constructor.
use Doctrine\Persistence\ManagerRegistry;
class SomeController {
public function __construct(private ManagerRegistry $doctrine) {}
public function someAction(Request $request) {
// access Doctrine
$this->doctrine;
}
}
You can use EntityManagerInterface $entityManager:
public function delete(Request $request, Test $test, EntityManagerInterface $entityManager): Response
{
if ($this->isCsrfTokenValid('delete'.$test->getId(), $request->request->get('_token'))) {
$entityManager->remove($test);
$entityManager->flush();
}
return $this->redirectToRoute('test_index', [], Response::HTTP_SEE_OTHER);
}
As per the answer of #yivi and as mentionned in the documentation, you can also follow the example below by injecting Doctrine\Persistence\ManagerRegistry directly in the method you want:
// src/Controller/ProductController.php
namespace App\Controller;
// ...
use App\Entity\Product;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\Response;
class ProductController extends AbstractController
{
/**
* #Route("/product", name="create_product")
*/
public function createProduct(ManagerRegistry $doctrine): Response
{
$entityManager = $doctrine->getManager();
$product = new Product();
$product->setName('Keyboard');
$product->setPrice(1999);
$product->setDescription('Ergonomic and stylish!');
// tell Doctrine you want to (eventually) save the Product (no queries yet)
$entityManager->persist($product);
// actually executes the queries (i.e. the INSERT query)
$entityManager->flush();
return new Response('Saved new product with id '.$product->getId());
}
}
Add code in controller, and not change logic the controller
<?php
//...
use Doctrine\Persistence\ManagerRegistry;
//...
class AlsoController extends AbstractController
{
public static function getSubscribedServices(): array
{
return array_merge(parent::getSubscribedServices(), [
'doctrine' => '?'.ManagerRegistry::class,
]);
}
protected function getDoctrine(): ManagerRegistry
{
if (!$this->container->has('doctrine')) {
throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
}
return $this->container->get('doctrine');
}
...
}
read more https://symfony.com/doc/current/service_container/service_subscribers_locators.html#including-services
In my case, relying on constructor- or method-based autowiring is not flexible enough.
I have a trait used by a number of Controllers that define their own autowiring. The trait provides a method that fetches some numbers from the database. I didn't want to tightly couple the trait's functionality with the controller's autowiring setup.
I created yet another trait that I can include anywhere I need to get access to Doctrine. The bonus part? It's still a legit autowiring approach:
<?php
namespace App\Controller;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager;
use Symfony\Contracts\Service\Attribute\Required;
trait EntityManagerTrait
{
protected readonly ManagerRegistry $managerRegistry;
#[Required]
public function setManagerRegistry(ManagerRegistry $managerRegistry): void
{
// #phpstan-ignore-next-line PHPStan complains that the readonly property is assigned outside of the constructor.
$this->managerRegistry = $managerRegistry;
}
protected function getDoctrine(?string $name = null, ?string $forClass = null): ObjectManager
{
if ($forClass) {
return $this->managerRegistry->getManagerForClass($forClass);
}
return $this->managerRegistry->getManager($name);
}
}
and then
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Entity\Foobar;
class SomeController extends AbstractController
{
use EntityManagerTrait
public function someAction()
{
$result = $this->getDoctrine()->getRepository(Foobar::class)->doSomething();
// ...
}
}
If you have multiple managers like I do, you can use the getDoctrine() arguments to fetch the right one too.
I want to fetch the user object in a controllers constructur in a Symfony 4.3.2 project. According to the docs on https://symfony.com/doc/4.0/security.html#retrieving-the-user-object, I just need to call $this->getUser(). And yes, this works in action methods.
BUT: trying to get the user in the constructor doesn't work, because the container will NOT be initialized here and the getUser method throws an exception "Call to a member function has() on null": the container is null at this point in time.
This works:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class TestController extends AbstractController
{
public function indexAction()
{
dump($this->getUser());
}
}
This doesn't:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class TestController extends AbstractController
{
public function __contruct()
{
dump($this->getUser());
}
public function indexAction()
{
}
}
And when I inject the container manually, then all is fine too:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class TestController extends AbstractController
{
public function __construct(ContainerInterface $container)
{
$this->container = $container;
dump($this->getUser());
}
public function indexAction()
{
}
}
btw, this is the getUser method in AbstractController:
protected function getUser()
{
if (!$this->container->has('security.token_storage')) {
throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
}
......
Is this a bug, that the container is not initialized in the constructor or is it a feature, that you have to initialize this by hand when you need the user in the constructor?
Edit: using the way shown in https://symfony.com/blog/new-in-symfony-3-2-user-value-resolver-for-controllers does work in actions, but it doesn't work in the constructor:
....
private $user;
public function __construct(UserInterface $user)
{
$this->user = $user;
}
produces the following error message: Cannot autowire service "App\Controller\TestController": argument "$user" of method "__construct()" references interface "Symfony\Component\Security\Core\User\UserInterface" but no such service exists. Did you create a class that implements this interface?. And that is where I would like to set the user object.
NEVER USE $security->getUser() or $this->getUser() in constructor!!
auth may not be complete yet. (In Service Instead, store the entire Security object. :
symfony.com/doc/security.html#a-fetching-the-user-object
... and you can use $this->getUser() in any Controller what extended with the AbstractController. (Just not in the constructor)
The container gets set by the ControllerResolver after the Controller has been instanced by calling the setContainer method that you mention. Thus, when the constructor is called the container is not available by design.
You might have a use case, but I don't see why you want to do this since in your controller methods you will have to access the $user property and it'll just save you typing get(). You can inject the whole container as shown in your sample or you can inject just the Security service.
use Symfony\Component\Security\Core\Security;
class TestController extends AbstractController
{
private $user;
public function __construct(Security $security)
{
$this->user = $security->getUser();
}
public function indexAction()
{
$user = $this->user; // Just saved you typing five characters
// At this point the container is available
}
}
I'm not actually setting the security service because it'll become available later through the container.
If you want to do this to enforce access control for the whole class you can use the Security annotations:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
/**
* #IsGranted('ROLE_USER')
*/
class TestController extends AbstractController
{
// Only authenticated user will be able to access this methods
}
First of all, I have to say that I have been seeing answers and documentation for several days but none of them answer my question.
The only and simple thing I want to do is to use the twig service as a global service in a BaseController.
This is my code:
<?php
namespace App\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Service\Configuration;
use App\Utils\Util;
abstract class BaseController extends Controller
{
protected $twig;
protected $configuration;
public function __construct(\Twig_Environment $twig,Configuration $configuration)
{
$this->twig = $twig;
$this->configuration = $configuration;
}
}
Then in all my controllers extend the twig and configuration service, without having to inject it again & again.
//...
//......
/**
* #Route("/configuration", name="configuration_")
*/
class ConfigurationController extends BaseController
{
public function __construct()
{
//parent::__construct();
$this->twig->addGlobal('menuActual', "config");
}
As you can see the only thing I want is to have some services global to have everything more organized and also to create some global shortcuts for all my controllers. In this example I am assigning a global variable to make a link active in the menu of my template and in each controller I have to add a new value for menuActual, for example in the UserController the variable would be addGlobal('menuActual', "users").
I think this should be in the good practices of symfony which I don't find :(.
Having to include the \Twig_Environment in each controller to assign a variable to the view seems very repetitive to me. This should come by default in the controller.
Thanks
I've had that problem as well - trying to not have to repeat a bit of code for every controller / action.
I solved it using an event listener:
# services.yaml
app.event_listener.controller_action_listener:
class: App\EventListener\ControllerActionListener
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
#src/EventListener/ControllerActionListener.php
namespace App\EventListener;
use App\Controller\BaseController;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
/**
* Class ControllerActionListener
*
* #package App\EventListener
*/
class ControllerActionListener
{
public function onKernelController(FilterControllerEvent $event)
{
//fetch the controller class if available
$controllerClass = null;
if (!empty($event->getController())) {
$controllerClass = $event->getController()[0];
}
//make sure your global instantiation only fires if the controller extends your base controller
if ($controllerClass instanceof BaseController) {
$controllerClass->getTwig()->addGlobal('menuActual', "config");
}
}
}
In Symfony 2.8/3.0, with our fancy new security components, how do I get the currently logged User (i.e. FOSUser) object in a service without injecting the whole container?
Is it even possible in a non-hacky way?
PS: Let's not consider the "pass it to the service function as a parameter" for being trivially obvious. Also, dirty.
Inject security.token_storage service into your service, and then use:
$this->token_storage->getToken()->getUser();
as described here: http://symfony.com/doc/current/book/security.html#retrieving-the-user-object and here: http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services
Works with Symfony 3.4, 4.x, 5.x & above. The Security utility class was introduced in Symfony 3.4.
use Symfony\Component\Security\Core\Security;
public function indexAction(Security $security)
{
$user = $security->getUser();
}
https://symfony.com/doc/3.4/security.html#always-check-if-the-user-is-logged-in
Using constructor dependency injection, you can do it this way:
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class A
{
private $user;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->user = $tokenStorage->getToken()->getUser();
}
public function foo()
{
dump($this->user);
}
}
In symfo 4 :
use Symfony\Component\Security\Core\Security;
class ExampleService
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function someMethod()
{
$user = $this->security->getUser();
}
}
See doc : https://symfony.com/doc/current/security.html#retrieving-the-user-object
From Symfony 3.3, from a Controller only, according this blog post: https://symfony.com/blog/new-in-symfony-3-2-user-value-resolver-for-controllers
It's easy as:
use Symfony\Component\Security\Core\User\UserInterface
public function indexAction(UserInterface $user)
{...}
With Symfony 5.2+ and PHP 8.0+ you can also get the logged user using the #[CurrentUser] attribute
namespace App\Controller;
use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
class FooController extends AbstractController
{
public function index(#[CurrentUser] ?User $user)
{
// ...
}
}
Blog post: https://symfony.com/blog/new-in-symfony-5-2-controller-argument-attributes
Documentation: https://symfony.com/doc/current/security.html
Symfony does this in Symfony\Bundle\FrameworkBundle\ControllerControllerTrait
protected function getUser()
{
if (!$this->container->has('security.token_storage')) {
throw new \LogicException('The SecurityBundle is not registered in your application.');
}
if (null === $token = $this->container->get('security.token_storage')->getToken()) {
return;
}
if (!is_object($user = $token->getUser())) {
// e.g. anonymous authentication
return;
}
return $user;
}
So if you simply inject and replace security.token_storage, you're good to go.
if you class extend of Controller
$this->get('security.context')->getToken()->getUser();
Or, if you has access to container element..
$container = $this->configurationPool->getContainer();
$user = $container->get('security.context')->getToken()->getUser();
http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
I'm trying to create a new User Admin from a fixture. I'm using FOSUserBundle and Symfony2.
$userManager = $this->container->get('fos_user.user_manager');
//$userAdmin = $userManager->createUser();
$userAdmin = new UserAdmin();
$userAdmin->setUsername('francis');
$userAdmin->setEmail('francis#francis.com');
$userAdmin->setEnabled(true);
$userAdmin->setRoles(array('ROLE_ADMIN'));
$userManager->updateUser($userAdmin, true);
I'm always getting this error:
[ErrorException]
Notice: Undefined property:
INCES\ComedorBundle\DataFixtures\ORM\LoadUserAdminData::$container in
/public_html/Symfony/src/INCES/ComedorBundle/DataFixtures/ORM/LoadUserAdminData.php line 16
This worked for me (i'm also using FOSUserBundle):
// Change the namespace!
namespace Acme\DemoBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LoadUserData implements FixtureInterface, ContainerAwareInterface
{
//.. $container declaration & setter
public function load(ObjectManager $manager)
{
// Get our userManager, you must implement `ContainerAwareInterface`
$userManager = $this->container->get('fos_user.user_manager');
// Create our user and set details
$user = $userManager->createUser();
$user->setUsername('username');
$user->setEmail('email#domain.com');
$user->setPlainPassword('password');
//$user->setPassword('3NCRYPT3D-V3R51ON');
$user->setEnabled(true);
$user->setRoles(array('ROLE_ADMIN'));
// Update the user
$userManager->updateUser($user, true);
}
}
Hope this helps someone! :)
Follow this section of the documentation.
The Error is because the $container is currently undefined. To fix this, add the ContainerAwareInterface to your class definition.
class LoadUserData implements FixtureInterface, ContainerAwareInterface
{
...
}
This will not completely get you what you want though, since you are creating the user without the UserManager. Instead you should be using the line you have commented out.
It seems to me that you don't need the UserAdmin class. The admin users should be a subset of the User distinguished only by the roles that they have.
You should use the UserManager to create a User(not UserAdmin) and set the roles.
If you need to keep an index of all admin users, a MySQL VIEW could accomplish this, or you could create your own custom "cache" table and use Doctrine Listeners to update it when needed.
This question is fairly old, so I am guessing you found the answer or at least a workaround.
Would you please provide that? It is ok to answer your own questions.
This is the updated version for SF3+
This answer is based on Anil and Mun Mun Das answers.
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use FOS\UserBundle\Model\UserManagerInterface;
class AdminFixtures extends Fixture
{
private $userManager;
public function __construct(UserManagerInterface $userManager)
{
$this->userManager = $userManager;
}
public function load(ObjectManager $manager)
{
$user = $this->userManager->createUser();
$user->setUsername('username');
$user->setEmail('email#domain.com');
$user->setPlainPassword('password');
$user->setEnabled(true);
$user->setRoles(array('ROLE_ADMIN'));
$this->userManager->updateUser($user);
}
}
This is what I did using Symfony 4, SonataAdmin and FosUserBundle
namespace App\DataFixtures;
use App\Application\Sonata\UserBundle\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
class UserFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
$user = new User();
$user->setUsername('yourusername');
$user->setEmail('youremail#email.com');
$user->setEnabled(true);
$user->setPlainPassword('yourpassword');
$user->setRoles(array('ROLE_SUPER_ADMIN'));
$manager->persist($user);
$manager->flush();
}
}