【问题标题】:Organize the models in Symfony 3在 Symfony 3 中组织模型
【发布时间】:2017-06-27 05:50:33
【问题描述】:

我刚刚阅读了 Symfony 3 官方文档,并指出当我需要从数据库中检索对象时,我应该使用如下内容:

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

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

【问题讨论】:

  • 在此示例中,我没有将产品更改为良好。在每种情况下,您都必须重构每一个部分。 Product::model() -> Good::model()'AppBundle:Product' -> 'AppBundle:Good'Product::class -> Good::class 不是吗?我认为最接近的是@COil Btw 的答案。学说在这里有不同的方法。模型不应该对数据库或存储库有任何了解。它应该具有尽可能少的依赖关系。好的 ides/plugins 也可以解决这个问题。

标签: php symfony doctrine-orm


【解决方案1】:

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

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

【讨论】:

  • 谢谢。我还没有尝试过,但看起来很不错。至少我没有看到引号 =)
【解决方案2】:

$em->getRepository('...') 返回混合数据类型(取决于第一个参数)。即使您编写$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();
 }

【讨论】:

    【解决方案3】:

    您可以像这样将存储库声明为服务:

    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 插件。服务的自动完成功能确实是必须的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-20
      • 2011-10-09
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 2020-05-19
      相关资源
      最近更新 更多