symfony4, Dependency injection, no default argument - php

I have setup service to controller function like this
App\Controller\Controller:
calls:
- [new, ['#request_stack','#doctrine.orm.default_entity_manager']]
I needed Entity Manager inside controller action and my function looks like this
public function new(RequestStack $request, EntityManager $em): Response
{
$currentRequest = $request->getCurrentRequest();
$data = json_decode($currentRequest->getContent(), true);
....
return new ApiResponse(['message' => $message['message'], 'body' => 'success']);
}
and when executing comes to line return new ApiResponse it gives error
Controller "Controller::new()" requires that you provide a value for the "$request" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.
How to get entity manager in controller action or how to resolve this problem?

As the Symfony 4 Doc on Doctrine says :
// you can fetch the EntityManager via $this->getDoctrine()
// or you can add an argument to your action: index(EntityManagerInterface $entityManager)
$entityManager = $this->getDoctrine()->getManager();
So you can just get the entity manager this way in your controller
However, you can also register the Entity Manager as a service to use it.
Be sure to set the autowire to true :
# config/services.yaml
services:
_defaults:
autowire: true
and register it as a service :
# config/services.yaml
services:
#....
controller_em:
class: App\Controller\Controller
arguments: [ '#doctrine.orm.default_entity_manager' ]
public: true
So that you can use it like so in your controller :
private $objectManager;
public function __construct(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
You can also use this way to use the Entity Manager in Voter or Manager.

well. you need to inject your stuff into controller's object constructor - that is called DI in Symfony-way (or via set-methods):
services.yml - if everything ok with your autowire
App\Controller\Controller:
calls:
- [new]
if not add it manually:
App\Controller\Controller:
arguments:
- '#doctrine.orm.default_entity_manager'
calls:
- [new]
Controller.php
/** #var EntityManager */
private $em;
public __construct(EntityManager $em)
{
$this->em = $em;
}
and then just use it in your method:
public function new(RequestStack $request): Response
{
$this->em ...
}

For your information you can create your own AbsractController to inject the EntityManager in all controller extending it like this.
<?php
namespace App\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as BaseController;
abstract class AbstractController extends BaseController
{
/**
* #var EntityManagerInterface
*/
protected $em;
/**
* #required
*
* #param EntityManagerInterface $em
*/
public function setEntityManager(EntityManagerInterface $em)
{
$this->em = $em;
}
}
If a controller extends this AbstractController, you could access $this->em everywhere in it.
The "required" annotation here is the key to enable what you tried to do without the need of adding configuration as you did. It's like adding a calls line in your configuration!
You could do something like this for every services you need in all your controllers.

Related

getDoctrine() null on Symfony 3.4

I have an error on a symfony 3.4 project.
I'm trying to manage the display of a notification in the menu of my application.
So I created a CustomController which extends Controller.
Then I made all my other controllers inherit from CustomController.
But when I make a call to getDoctrine() to reach a repository I get the following error:
"Call to a member function has() on null"
Here is my CustomController:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class CustomController extends Controller
{
public $data = [];
protected $em;
public function __construct()
{
$this->em = $this->getDoctrine()->getManager();
$countAttente = $this->em->getRepository('AppBundle:Commandes')->tailleEnAttente("En attente");
$this->data['countAttente'] = $countAttente;
}
}
I tried to pass the controller as a service in service.yml but it did not change anything
AppBundle\Controller\CustomController:
class: AppBundle\Controller\CustomController
arguments: ["#doctrine.orm.entity_manager"]
calls:
- [setContainer, ["#service_container"]]
I found many similar topics on this type of error but none of them allowed me to skip this error
Any help is welcome
Autowire your EntityManager directly inside your constructor:
use Doctrine\ORM\EntityManagerInterface;
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
Or if you need a specific repository, and autowired is set up with the default configuration you can do the same as well with the repository:
private $repository;
public function __construct(CommandesRepository $repository)
{
$this->repository = $repository;
}

FOSUserBundle event REGISTRATION_INITIALIZE not triggered

I wanted to set password automatically when one register the form. So I use REGISTRATION_INITIALIZE to trigger the event. Unfortunately it's not working.
Listener:
<?php
namespace Acme\UserBundle\EventListener;
use Doctrine\ORM\EntityManager;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class RegistrationListener implements EventSubscriberInterface
{
/**
* #var EntityManager
*/
private $em;
/**
* #param \Doctrine\ORM\EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
/**
* {#inheritdoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_INITIALIZE => 'onRegistrationInit',
);
}
public function onRegistrationInit(UserEvent $userEvent)
{
$user = $userEvent->getUser();
$user->setPassword('abcdeffffff');
}
Services:
#src/Acme/UserBundle/Resources/config/services.yml
services:
acme_user.registration:
class: Acme\UserBundle\EventListener\RegistrationListener
arguments:
entityManager: "#doctrine.orm.entity_manager"
tags:
- { name: kernel.event_subscriber}
So the password is not setting and it shows the password should not be blank.
What am I doing wrong? Any help!
EDIT:
The problem was I was defining service at the wrong place.
Instead of src/Acme/UserBundle/Resources/config/services.yml, It should be app/config/services.yml.
I saw src/Acme/UserBundle/Resources/config/services.ymlin http://symfony.com/doc/master/bundles/FOSUserBundle/controller_events.html, But was not working for me!
Maybe I am wrong, but I think your service definition uses features from Symfony 3.3 but you are using Symfony 3.2.8, e.g.
New in version 3.3: The ability to configure an argument by its name ($adminEmail) was added in Symfony 3.3. Previously, you could configure it only by its index (2 in this case) or by using empty quotes for the other arguments.
Try updating your service definition to:
#src/Acme/UserBundle/Resources/config/services.yml
services:
acme_user.registration:
class: Acme\UserBundle\EventListener\RegistrationListener
arguments: ["#doctrine.orm.entity_manager"]
tags:
- { name: kernel.event_subscriber}
And a remark: as you are actually using a subscriber you should rename the class RegistrationListener to RegistrationSubscriber.

how can i access to the entity repository from a entity listener in symfony 2.8?

I'm new in Symfony 2.
I have a function called "addNewTarjeta" in a personalized entity respository.
<?php
namespace Elkanogroup\ClientesBundle\Repository;
/**
* ClienteRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ClienteRepository extends \Doctrine\ORM\EntityRepository {
/**
* Asigna una tarjeta a este cliente.
*/
public function addNewTarjeta(Cliente $cliente) {
$tarjeta = new \Elkanogroup\ClientesBundle\Entity\Tarjeta();
$tarjeta->setNumeroTarjeta('5555 5555 5555 5555');
$tarjeta->setCliente($cliente);
$tarjeta->setFechaExpedicion(new \DateTime());
$em = $this->getDoctrine()->getManager();
$em->persist($tarjeta);
$flush = $em->flush();
if ($flush != null) {
return false;
}
return true;
}
I have a listener waiting for a doctrine event postPersist. I would like to call to "addNewTarjeta" from a postPersist function.
I'm trying to do something like this:
<?php
namespace Elkanogroup\ClientesBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Elkanogroup\ClientesBundle\Entity\Cliente;
use Elkanogroup\ClientesBundle\Repository\ClienteRepository;
class ClienteListener {
public function postPersist(Cliente $cliente, LifecycleEventArgs $args) {
$cliente->addNewTarjeta($cliente);
}
But it doesnt work. Symfony says:
Attempted to call an undefined method named "addNewTarjeta" of class
"Elkanogroup\ClientesBundle\Entity\Cliente".
Can anyone help me ?? Thanks and sorry for my bad english.
Everyone here says that you need to inject the entity manager but to me it's not true: you can retrive it from LifecycleEventArgs without inject anything.
Just do
$args->getObjectManager();
and you're done.
Just a note: usually repos are used to keep custom queries (via DQL or plain SQL or query builder). A logic like this should be fitted inside a service (a manager, helper or whatever).
As #dragoste said, you need to inject the entitymanager service into your listener.
It can be done in services.yml:
name.of.your.listener:
class: AppBundle\Listener\MyListener
arguments: ["#doctrine.orm.entity_manager"]
And then, add a public function __construct(\Doctrine\ORM\EntityManager $entityManager) method in your listener:
<?php
namespace AppBundle\Listener;
class MyListener
{
/**
* #var \Doctrine\ORM\EntityManager
*/
private $entityManager;
public function __construct(\Doctrine\ORM\EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}

Symfony 2 EntityManager injection in service

I've created my own service and I need to inject doctrine EntityManager, but I don't see that __construct() is called on my service, and injection doesn't work.
Here is the code and configs:
<?php
namespace Test\CommonBundle\Services;
use Doctrine\ORM\EntityManager;
class UserService {
/**
*
* #var EntityManager
*/
protected $em;
public function __constructor(EntityManager $entityManager)
{
var_dump($entityManager);
exit(); // I've never saw it happen, looks like constructor never called
$this->em = $entityManager;
}
public function getUser($userId){
var_dump($this->em ); // outputs null
}
}
Here is services.yml in my bundle
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments:
entityManager: "#doctrine.orm.entity_manager"
I've imported that .yml in config.yml in my app like that
imports:
# a few lines skipped, not relevant here, i think
- { resource: "#TestCommonBundle/Resources/config/services.yml" }
And when I call service in controller
$userservice = $this->get('test.common.userservice');
$userservice->getUser(123);
I get an object (not null), but $this->em in UserService is null, and as I already mentioned, constructor on UserService has never been called
One more thing, Controller and UserService are in different bundles (I really need that to keep project organized), but still: everyting else works fine, I can even call
$this->get('doctrine.orm.entity_manager')
in same controller that I use to get UserService and get valid (not null) EntityManager object.
Look like that I'm missing piece of configuration or some link between UserService and Doctrine config.
Your class's constructor method should be called __construct(), not __constructor():
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments: [ "#doctrine.orm.entity_manager" ]
And then they would be available in the order they were listed via the arguments (if there are more than 1).
public function __construct(EntityManager $entityManager) {
$this->em = $entityManager;
}
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.
Check my post How to use Repository with Doctrine as Service in Symfony for more general description.
To your specific case, original code with tuning would look like this:
1. Use in your services or Controller
<?php
namespace Test\CommonBundle\Services;
use Doctrine\ORM\EntityManagerInterface;
class UserService
{
private $userRepository;
// use custom repository over direct use of EntityManager
// see step 2
public function __constructor(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function getUser($userId)
{
return $this->userRepository->find($userId);
}
}
2. Create new custom repository
<?php
namespace Test\CommonBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
class UserRepository
{
private $repository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->repository = $entityManager->getRepository(UserEntity::class);
}
public function find($userId)
{
return $this->repository->find($userId);
}
}
3. Register services
# app/config/services.yml
services:
_defaults:
autowire: true
Test\CommonBundle\:
resource: ../../Test/CommonBundle

Injecting SecurityContext into a Listener prePersist or preUpdate in Symfony2 to get User in a createdBy or updatedBy Causes Circular Reference Error

I setup a listener class where i'll set the ownerid column on any doctrine prePersist. My services.yml file looks like this ...
services:
my.listener:
class: App\SharedBundle\Listener\EntityListener
arguments: ["#security.context"]
tags:
- { name: doctrine.event_listener, event: prePersist }
and my class looks like this ...
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\SecurityContextInterface;
class EntityListener
{
protected $securityContext;
public function __construct(SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
}
/**
*
* #param LifecycleEventArgs $args
*/
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
$entity->setCreatedby();
}
}
The result of this is the following error.
ServiceCircularReferenceException: Circular reference detected for service "doctrine.orm.default_entity_manager", path: "doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection -> my.listener -> security.context -> security.authentication.manager -> fos_user.user_manager".
My assumption is that the security context has already been injected somewhere in the chain but I don't know how to access it. Any ideas?
I had similar problems and the only workaround was to pass the whole container in the constructor (arguments: ['#service_container']).
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
class MyListener
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
// ...
public function prePersist(LifeCycleEventArgs $args)
{
$securityContext = $this->container->get('security.context');
// ...
}
}
As of Symfony 2.6 this issue should be fixed. A pull request has just been accepted into the master. Your problem is described in here.
https://github.com/symfony/symfony/pull/11690
As of Symfony 2.6, you can inject the security.token_storage into your listener. This service will contain the token as used by the SecurityContext in <=2.5. In 3.0 this service will replace the SecurityContext::getToken() altogether. You can see a basic change list here: http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements#deprecated-the-security-context-service
Example usage in 2.6:
Your configuration:
services:
my.entityListener:
class: App\SharedBundle\Listener\EntityListener
arguments:
- "#security.token_storage"
tags:
- { name: doctrine.event_listener, event: prePersist }
Your Listener
namespace App\SharedBundle\Listener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class EntityListener
{
private $token_storage;
public function __construct(TokenStorageInterface $token_storage)
{
$this->token_storage = $token_storage;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$entity->setCreatedBy($this->token_storage->getToken()->getUsername());
}
}
For a nice created_by example, you can use https://github.com/hostnet/entity-blamable-component/blob/master/src/Listener/BlamableListener.php for inspiration. It uses the hostnet/entity-tracker-component which provides a special event that is fired when an entity is changed during your request. There's also a bundle to configure this in Symfony2
https://github.com/hostnet/entity-tracker-component
https://github.com/hostnet/entity-tracker-bundle
There's a great answer already in this thread but everything changes. Now there're entity listeners classes in Doctrine:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners-class
So you can add an annotation to your entity like:
/**
* #ORM\EntityListeners({"App\Entity\Listener\PhotoListener"})
* #ORM\Entity(repositoryClass="App\Repository\PhotoRepository")
*/
class Photo
{
// Entity code here...
}
And create a class like this:
class PhotoListener
{
private $container;
function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/** #ORM\PreRemove() */
public function preRemoveHandler(Photo $photo, LifecycleEventArgs $event): void
{
// Some code here...
}
}
Also you should define this listener in services.yml like that:
photo_listener:
class: App\Entity\Listener\PhotoListener
public: false
autowire: true
tags:
- {name: doctrine.orm.entity_listener}
I use the doctrine config files to set preUpdate or prePersist methods:
Project\MainBundle\Entity\YourEntity:
type: entity
table: yourentities
repositoryClass: Project\MainBundle\Repository\YourEntitytRepository
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
lifecycleCallbacks:
prePersist: [methodNameHere]
preUpdate: [anotherMethodHere]
And the methods are declared in the entity, this way you don't need a listener and if you need a more general method you can make a BaseEntity to keep that method and extend the other entites from that. Hope it helps!
Symfony 6.2.4
Add this in your Entity :
#[ORM\EntityListeners(["App\Doctrine\MyListener"])]
Add this in your services.yaml:
App\Doctrine\MyListener:
tags: [doctrine.orm.entity_listener]
Then you can do this :
<?php
namespace App\Doctrine;
use App\Entity\MyEntity;
use Symfony\Component\Security\Core\Security;
class MyListener
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function prePersist(MyEntity $myEntity)
{
//Your stuff
}
}
Hope it helps.

Categories