简体   繁体   English

依赖注入和模型实体 - 正确的方法?

[英]Dependency injection and Model entities - the right way ?

My symfony2 application has the following structure: 我的symfony2应用程序具有以下结构:

There is a service data_provider , which gets data from various external sources and represents it as entity objects. 有一个服务data_provider ,它从各种外部源获取数据并将其表示为实体对象。

Some objects has relations. 有些对象有关系。 Currently I am loading relations in controller or helper-services if needed. 目前我正在加载控制器或帮助器服务中的关系,如果需要的话。

It is not very convenient, sometimes I want to get relations from my entity ojbect. 它不是很方便,有时我想从我的实体ojbect获得关系。 To do this I need access to data_provider service. 为此,我需要访问data_provider服务。

I want to implement something like doctrine lazy-loading, what is the right way of doing this ? 我想实现像doctrine lazy-loading这样的东西,这样做的正确方法是什么?

Some obvious solutions - to inject data_provider in every entity instacne, or to some static property, or to make some static methods in service, or to use evenet dispatcher, but I don't think it is the right way 一些明显的解决方案 - 在每个实体instacne或一些静态属性中注入data_provider ,或者在服务中制作一些静态方法,或者使用evenet调度程序,但我不认为这是正确的方法

Made some research of ObjectManagerInterface as Cerad suggested, and found this peace of code: https://github.com/doctrine/common/blob/master/lib/Doctrine/Common/Persistence/PersistentObject.php 对Cerad建议对ObjectManagerInterface进行了一些研究,并发现了代码的和平: https//github.com/doctrine/common/blob/master/lib/Doctrine/Common/Persistence/PersistentObject.php

PersistentObject implements ObjectManagerAware interface, it has private static property where ObjectManager is stored. PersistentObject实现了ObjectManagerAware接口,它具有存储ObjectManager的私有静态属性。

So I ended with this: 所以我结束了这个:

class DataProvider
{
    public function __construct() 
    {
        ...
        AbstractEntity::setDataProvider($this);
    }
}

abstract class AbstractEntity
{
    private static $dataProvider;
    public static function setDataProvider() {...};
    protected static function getDataProvider() {...};
}

The main purpose of services in Symfony (and not only) is exactly this one - to deliver distinguished functionalitys globally over your project. Symfony(而不仅仅是)服务的主要目的正是为了在全球范围内为您的项目提供卓越的功能。

In this regard, a single service, in your case - dataProvider, should always deliver a single entity. 在这方面,单个服务(在您的情况下 - dataProvider)应始终提供单个实体。 If you have to deal with multiple entities returned from one data source, wrap the data source deliverer into a service itself, and then define one service per each entity with the deliverer injected into it. 如果必须处理从一个数据源返回的多个实体,请将数据源传递器包装到服务本身中,然后为每个实体定义一个服务,并将传递器注入其中。

Then you can inject the respective entity services into your controllers. 然后,您可以将相应的实体服务注入控制器。

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

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