Generate entities with mappers

2019-07-25 15:48发布

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条回答
\"骚年 ilove
2楼-- · 2019-07-25 16:16

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.

查看更多
登录 后发表回答