symfony4 - Symfony 4. ServiceEntityRepository 与 EntityRepository

标签 symfony4

为什么我需要在我的存储库中扩展 ServiceEntityRepository?
在 Symfony 3.4 中,我总是扩展 EntityRepository。使用 ServiceEntityRepository 我在这里描述了一个奇怪的问题 Symfony 4. InheritanceType("JOINED") and ParamConverter. Strange phenomenon

最佳答案

这是我的 2 美分:你不需要,但你应该。为什么 ?因为它允许您使用 Autowiring (这是 SF4 中的一大改进,也是开发的乐趣)

class ProductRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, Product::class);
    }
}

然后你可以像这样到处自动编写:

// 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());
}

如果你不想,不用担心,只需使用旧的方式:

// 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());
}

关于symfony4 - Symfony 4. ServiceEntityRepository 与 EntityRepository,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55179959/

相关文章:

php - Symfony 手动连接参数 - 'arguments' 与 'bind'

php - 如何为特定环境覆盖 Symfony 的安全性?

symfony4 在服务中使用 .env 配置变量

symfony - 数据转换器与约束

php - 如何在for循环中打印所有结果?

symfony4 - Dropzone 和 webpack encore

Symfony 4 错误安装 sensio/generator-bundle for sonata admin bundle

php - Symfony 4 每个项目存储库有一个以上的应用程序

composer-php - symfony 4.0 无法安装 assetic-bundle

javascript - 使用 WebPack Encore 和 Symfony 4 在 TWIG 页面上使用函数 Javascript