Generate entities with mappers

我的梦境 提交于 2019-12-13 00:34:41

问题


I am trying to find the best way to generate an enities, this is what I am doing at the moment.

I create an entity trough a mapper and a hydrator like this:

namespace Event\Model\Mapper;

use ZfcBase\Mapper\AbstractDbMapper;

class Event extends AbstractDbMapper
{
    protected $tableName  = 'events';

    public function findEventById($id)
    {
       $id = (int) $id;

       $select = $this->getSelect($this->tableName)
                      ->where(array('event_index' => $id));

       $eventEntity = $this->select($select)->current();  

     if($eventEntity){

        //Set Location Object
        $locationMapper = $this->getServiceLocator()->get('location_mapper');       
        $locationEntity = $locationMapper->findlocationById($eventEntity->getLocationIndex());          
        $eventEntity->setLocationIndex($locationEntity);

        //Set User Object
        $userMapper = $this->getServiceLocator()->get('user_mapper');
        $userEntity = $userMapper->findUserById($eventEntity->getEnteredBy());
        $eventEntity->setEnteredBy($userEntity);

        //Set Catalog Object
        $catalogMapper = $this->getServiceLocator()->get('catalog_mapper');
        $catalogEntity = $catalogMapper->findCatalogById($eventEntity->getCatalogIndex());
        $eventEntity->setCatalogIndex($catalogEntity);          
    }


    return $eventEntity;
   }
}

Now the problem with this approach is that when I call let say the User entity this entity has other entities attach to it so when I generate the Event entity by inserting the User entity my Event entity becomes very large and bulky, I dont want that I just want the first layer of the "gerontology tree".

So I was thinking on creating a EventEntityFactory where I can bind together the child entities of the Event enity, I was planning on doing a factory for this.

Is there a better way of doing this?

Thanks


回答1:


One approach would be to use Virtual Proxies (with lazy loading):

http://phpmaster.com/intro-to-virtual-proxies-1/

http://phpmaster.com/intro-to-virtual-proxies-2/

Basically you would generate your entity, and replace any related entities with a light weight proxy object. this object would only load the related entity when required via lazy loading.

I've used this approach many times along with the Datamapper design pattern and it works very well.



来源:https://stackoverflow.com/questions/14404524/generate-entities-with-mappers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!