为什么我需要在我的存储库中扩展 ServiceEntityRepository?在 Symfony 3.4 中,我总是扩展 EntityRepository。使用 ServiceEntityRepository 我在这里描述了一个奇怪的问题Symfony 4. InheritanceType("JOINED") 和 ParamConverter。奇怪的现象
小智 9
这是我的 2 美分:你不需要,但你应该。为什么 ?因为它允许您使用自动装配(这是 SF4 中的一大改进,也是开发的乐趣)
class ProductRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Product::class);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样到处自动编写:
// From product controller
public function show(?int $id, ProductRepository $repository)
{
$product = $repository->find($id);
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
return new Response('Check out this great product: '.$product->getName());
}
Run Code Online (Sandbox Code Playgroud)
如果你不想,不用担心,只需使用旧的方式:
// From product controller
public function show(?int $id, EntityManagerInterface $manager)
{
$product = $manager->getRepository(Product::class)->find($id);
// or this one but only in a controller which extend AbstractController
$product = $this->getDoctrine()->getRepository(Product::class)->find($id);
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
return new Response('Check out this great product: '.$product->getName());
}
Run Code Online (Sandbox Code Playgroud)
当我在观看 Symfony 4 的培训视频时问同样的问题时,我遇到了这个问题。(我也尝试了你的实际问题。)
从我所看到的代码来看,您不需要使用较新的 ServiceEntityRepository 类,但它是一个改进。它所做的就是用修改后的构造函数包装 EntityRepository 类,使您需要传递的参数对开发人员更友好,并利用自动装配的优势。
作为一个例子,我在 Symfony 版本 3 中手动连接了我的自定义存储库(扩展EntityRepository ),在services.yml文件中使用如下代码:
Fully\Qualified\Namespace\MyCustomRepository:
factory: ["@doctrine.orm.entity_manager", getRepository]
arguments: [Fully\Qualified\Namespace\Entity\MyEntity]
Run Code Online (Sandbox Code Playgroud)
借助较新的ServiceEntityRepository类和版本 4 的增强型自动装配,我可以消除所有这些手动装配工作,并让服务容器来完成这项工作。
| 归档时间: |
|
| 查看次数: |
4863 次 |
| 最近记录: |