Symfony 5 中存储库的循环引用

Circular reference for Repository in Symfony 5

我尝试按照本教程进行操作:https://www.thinktocode.com/2018/03/05/repository-pattern-symfony/

它应该有助于构建您的存储库。

但是当我说到这里时:

final class ProductRepository
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * @var ObjectRepository
     */
    private $objectRepository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
        $this->objectRepository = $this->entityManager->getRepository(Product::class);
    }
    
    public function find(int $productId): Product
    {
        $product = $this->objectRepository->find($productId);
        return $product;
    }

    public function findOneByTitle(string $title): Product
    {
        $product = $this->objectRepository
            ->findOneBy(['title' => $title]);
        return $product;
    }

    public function save(Product $product): void
    {
        $this->entityManager->persist($product);
        $this->entityManager->flush();
    }
}

并使用此测试用例测试我的存储库:

<?php

namespace App\Tests\Repository;

use App\Repository\ProductRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class ProductRepository_KernelTest extends KernelTestCase
{

    private ?ProductRepository $_productRepository;

    protected function setUp(): void
    {
        $kernel = self::bootKernel();
        $this->_productRepository = self::$container->get(ProductRepository::class);
    }

    public function test_findAllProductNatByLabelForLabelEmptyReturnTenProduct()
    {
        dump($this->_productRepository->findAllProductsByLabel('AACIFEMINE'));
        die();
    }
}

无限循环。

我认为这是由于这段代码造成的:

public function __construct(EntityManagerInterface $entityManager)
{
    $this->entityManager = $entityManager;
    $this->objectRepository = $this->entityManager->getRepository(Product::class); // <-----
}

因为它在同一个构造函数中调用 ProductRepository 构造函数...所以我想这就是循环的原因

所以我不知道。本教程是错误的还是不是最新的?

https://www.thinktocode.com/2018/03/05/repository-pattern-symfony/#comment-4155200782

Maciej,

You are correct that in these example we are using 2 repositories. The object repository from doctrine inside our own custom repository. This allows use to be decoupled from doctrine's repository and still change this in the future. This means to not set your custom repository as the default repository in your entity.

You can get rid of inject the object repository, and in so only be using 1 repository by implementing a BaseRepository class in which you create the basic findBy, findOneBy, createQueryBuilder yourself. Take a look at the EntityRepository in Doctrine/ORM. This might be a good follow up topic to go over in a future article to create a better solution then I suggested in here.