06.
Controllers as Services
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
Whoops, an error! Please, try again later.
8 Comments
Hello, I'm trying to call an action from a controller to another controller.
So I've UserController and "getRegistrationNumberAction(Event $event)" and from EventController I call
$number= $this->get(UserController::class)->getRegistrationNumberAction($workEvent);
The error appear here:
$em= $this->getDoctrine()->getManager();
and the error is: Call to a member function has() on null
I've modified services.yml with new symfony configurations (autowire, _defaults, etc) so I can't understand what is wrong. Can you help me?
PS: If I try to dump $this->get(UserController::class) it dump null.
Thanks
Hey Nicola
I wouldn't recommend to call a controller's action inside another controller, what are you trying to achieve?
You may like to know that you can initiate another request (call a controllers action) inside a twig's template (More info here: https://symfony.com/doc/cur...
Cheers!
Hello MolloKhan , I've an action (getRegistrationNumber) that count users registered to an event and add 1. It's just a test but I want to add some users to an event not just with UserController but with EventController; so, from EventController, I need to know the registration number and the best way to do that was to call the action from UserController. Do you have a better idea? Thanks :-)
Ohh I got you. Of course a I have some ideas, but maybe not good ones! :P
In that case I would move all that logic to the UserRepository, so you can ask him about the registration number of the user and to do the sum up
And calling it from EventController would be as easy as
Great idea..I'll try :-) just a question: if using action from one controller to another isn't recommended, why add Controller as Services in 3.3?
Excellent question, is known that you can use a controller just like a service, but the idea is to take advantage of the "dependency injection" in your controller's actions, instead of retrieving services from the container
Thank you, I need to study more about dependency injection. BTW I've moved the logic to user Repository and It works great. Thank you :-)
Awesome!
Let's keep learning ;)
"Houston: no signs of life"
Start the conversation!