[英]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
馬切伊,
您是對的,在這些示例中我們使用了 2 個存儲庫。 來自我們自己的自定義存儲庫中的學說的對象存儲庫。 這允許使用與學說的存儲庫分離,並且在未來仍然可以改變這一點。 這意味着不要將您的自定義存儲庫設置為實體中的默認存儲庫。
您可以擺脫注入對象存儲庫,因此僅通過實現 BaseRepository 類來使用 1 個存儲庫,您可以在其中創建基本的 findBy、findOneBy、createQueryBuilder。 查看 Doctrine/ORM 中的 EntityRepository。 這可能是一個很好的后續主題,可以在以后的文章中討論以創建更好的解決方案,然后我在這里建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.