如何解决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,
您是正确的,在这些示例中,我们使用2个存储库。的 来自我们自己的自定义存储库中的学说的对象存储库。这个 允许将使用与学说的存储库分离,并且仍然可以更改 将来会这样。这意味着不要将您的自定义存储库设置为 您实体中的默认存储库。
您可以摆脱注入对象存储库的麻烦,因此只能 通过实现BaseRepository类在其中使用1个存储库 自己创建基本的findBy,findOneBy,createQueryBuilder。采取 在Doctrine / ORM中查看EntityRepository。这可能很好 跟进主题以在以后的文章中讨论以创建更好的主题 解决方案,然后我在这里建议。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。