简体   繁体   English

用于Symfony2中性能的Doctrine自定义DQL或循环

[英]Doctrine custom DQL or Loop for performance in Symfony2

A Company object can have many Site Objects. 公司对象可以具有许多站点对象。 For a given company I'd like to know the primary Site. 对于给定的公司,我想了解主要站点。 (isPrimary is an attribute of Site). (isPrimary是Site的属性)。

I wrote a function in the Company class called getPrimarySite() and implemented it like this. 我在Company类中编写了一个名为getPrimarySite()的函数,并像这样实现了它。

public function getPrimarySiteForCompany()
    {
        foreach($this->getSite() as $site)
        {
            if($site->isPrimary())
            {
                return $site;
            }
        }

        return false;
    }

Is this OK or is it better to write a custom repository function in CompanyRepository where I get the primary Site with DQL? 这样可以吗,还是在CompanyDpository中编写一个自定义存储库函数更好,在该仓库中我可以通过DQL获得主站点?

If a company can only have one primary site, the natural solution would be to add a new property Company::$primarySite to the Company entity. 如果公司只能有一个主要站点,自然的解决方案是向Company实体添加一个新的属性Company::$primarySite This would be a [One|Many]ToOne relation (depending on whether or not one site can belong to more than one company). 这将是一个[One | Many] ToOne关系(取决于一个站点是否可以属于多个公司)。 Lookups will be fast, and your data layer then enforces the logic that a company can have only one primary site. 查找将很快,然后您的数据层将强制执行这样的逻辑:公司只能拥有一个主站点。 That makes more sense than having an isPrimary flag on the site, and then having to make sure that two sites belonging to the same company don't have that flag set at the same time. 这比在站点上具有isPrimary标志,然后必须确保属于同一公司的两个站点没有同时设置该标志更有意义。

While it wouldn't be hard to write a custom repository function to join the data and prevent lazy loading, this is a good example of premature optimization . 尽管编写自定义存储库函数来连接数据并防止延迟加载并不难,但这是过早优化的一个很好的例子。

Leave it as is for now and once everything works in production, you can go back to dev and use the profiler to see what could be improved performance-wise. 暂时保持现状,一旦一切都可以在生产中使用,您可以返回到dev并使用事件探查器来查看可以在性能方面进行哪些改进。 Additionally, if you only expect a few Site objects, then it probably doesn't matter all that much, if at all. 此外,如果只期望几个Site对象,那么可能就没关系了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM