在Symfony 3中组织模型

5

我刚刚阅读了官方的Symfony 3文档,当我需要从数据库中检索对象时,应该使用类似于以下的代码:

$repository = $em->getRepository('AppBundle:Product');

这里的Product只是一个没有父类的实体类,因此Doctrine通过注解来处理它。但我不确定在引号中硬编码模型名称是否是个好主意。如果我后来决定把模型命名为Good,我需要在整个项目中搜索并替换Product为Good吗?例如,在Laravel中,每个模型都扩展了基础模型类,所以我可以写成:Product::model()->find('nevermind')。在Symfony 3.3中有这样的选项吗?


我没有理解这个例子中将Product更改为Good的意思。在每种情况下,您都必须重构每个单独的部分。Product::model() -> Good::model()'AppBundle:Product' -> 'AppBundle:Good'Product::class -> Good::class,是吗?我认为最接近的答案是@COil的回答。顺便说一句,Doctrine在这里有不同的方法。模型不应该知道任何关于数据库或存储库的信息。它应该尽可能少地依赖。好的IDE /插件也可以解决此问题。 - Tomsgu
3个回答

4

我不确定这是否是解决您问题的方法,但您可以写:

$repository = $em->getRepository(Product::class);

谢谢。我还没有尝试过,但看起来相当不错。至少我没有看到引号 =) - James May

1

$repository = $em->getRepository(Product::class);返回的是混合数据类型(取决于第一个参数)。即使您编写了这样的代码,$repository = $em->getRepository(Product::class);,IDE也无法解析真实的数据类型。我建议使用以下方法(伪代码):

/**
 * Get product repo
 *
 * @return ProductRepository
 */
 public function getProductRepository() 
 {
     return $this->getEntityManager()->getRepository(Product::class);
 }

 /**
  * @return \Doctrine\ORM\EntityManager
  */
 public function getEntityManager(): EntityManager
 {
     return $this->getDoctrine()->getManager();
 }

1
您可以像这样将存储库声明为服务:
services:
    app.product_repo:
        class: AppBundle\Entity\ProductRepository
        factory: ['@doctrine.orm.default_entity_manager', getRepository]
        arguments:
            - AppBundle\Entity\Product

然后在你的控制器中:
$repository = $em->get('app.product_repo');

至少在PHPStorm和其Symfony插件中,它可以正常工作。拥有服务自动完成功能确实是必需的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接