dongtun3328 2016-09-22 19:46
浏览 83
已采纳

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

My symfony2 application has the following structure:

There is a service data_provider, which gets data from various external sources and represents it as entity objects.

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. To do this I need access to data_provider service.

I want to implement something like doctrine lazy-loading, what is the right way of doing this ?

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

  • 写回答

2条回答 默认 最新

  • dsxxqndv41105 2016-09-29 18:33
    关注

    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

    PersistentObject implements ObjectManagerAware interface, it has private static property where ObjectManager is stored.

    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() {...};
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算