Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Doctrine] Using Entity Manager autowiring in Repository for Multiple Entity Managers #20214

Open
wants to merge 1 commit into
base: 7.1
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions doctrine/multiple_entity_managers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -273,4 +273,40 @@

You should now always fetch this repository using ``ManagerRegistry::getRepository()``.

To correctly autowiring entity manager to the repository, set the name of the EntityManagerInterface parameter in the conststructor with a prefix ($***EntityManager) some as the name of the entity_manager in doctrine.yaml::

Check failure on line 276 in doctrine/multiple_entity_managers.rst

View workflow job for this annotation

GitHub Actions / Lint (DOCtor-RST)

Please reorder the use statements alphabetically

// src/Repository/CustomerRepository.php
namespace App\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\EntityManagerInterface;
use AcmeStoreBundle\Entity\Customer;

Check failure on line 283 in doctrine/multiple_entity_managers.rst

View workflow job for this annotation

GitHub Actions / Code Blocks

[Missing class] Class, interface or trait with name "AcmeStoreBundle\Entity\Customer" does not exist

class CustomerRepository extends EntityRepository
{
public function __construct(EntityManagerInterface $customerEntityManager)
{
parent::__construct($customerEntityManager, $customerEntityManager->getClassMetadata(Customer::class));
}
}

You should now simply autowiring this repository in controller::

// src/Controller/UserController.php
namespace App\Controller;
use App\Repository\CustomerRepository;

// ...

class UserController extends AbstractController
{
public function index(CustomerRepository $customerRepository): Response
{
// Just use of the repository some as repository from default Entity Manager
$customers = $customerRepository->findAll();

// ...
}
}

.. _`several alternatives`: https://stackoverflow.com/a/11494543
Loading