user2554865 user2554865 - 2 months ago 9
PHP Question

Dependency injection and Model entities - the right way ?

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

Answer

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() {...};
}