使用映射器生成实体 [英] Generate entities with mappers

查看:28
本文介绍了使用映射器生成实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找生成实体的最佳方式,这就是我目前正在做的事情.

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;
   }
}

现在这种方法的问题是,当我调用 User 实体时,这个实体有其他实体附加到它,所以当我通过插入 User 实体生成 Event 实体时,我的 Event 实体变得非常大和笨重,我不想要我只想要老年学树"的第一层.

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".

所以我想创建一个 EventEntityFactory,我可以将 Event 实体的子实体绑定在一起,我计划为此做一个工厂.

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?

谢谢

推荐答案

一种方法是使用虚拟代理(延迟加载):

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.

我已经多次将这种方法与 Datamapper 设计模式一起使用,并且效果很好.

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

这篇关于使用映射器生成实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆