如何通过实体正确初始化延迟集合?

时间:2014-09-03 13:02:17

标签: php doctrine-orm

我需要通过自己使用实体来初始化集合。我的意思是,我可以用Java实现,如下所示: 我会从StatelesBean类调用该方法。

那么,我怎么能用php方式呢?如果有人可以编写示例代码,我将不胜感激。

@Transient
public void initialize(Collection collection, int levelCursor, int level)
{
    if (collection instanceof PersistentBag)
    {
        if (ObjectUtil.isNull(((PersistentBag)collection).getSession()))
            return;
        else
        {
            Iterator itr = ((Collection)collection).iterator();
            while (itr.hasNext())
            {
                if (levelCursor < level)
                    ((SuperEntity)itr.next()).initialize(levelCursor, level);
                else
                    itr.next();
            }
        }
    } else
    {
        Iterator itr = ((Collection)collection).iterator();
        while (itr.hasNext())
        {
            if (levelCursor < level)
                ((SuperEntity)itr.next()).initialize(levelCursor, level);
            else
                itr.next();
        }
    }
}

/**
 * Searches for column and join column annotations for getter methods.
 * If found then tries to initialize childs
 * @param levelCursor
 * @param level
 */
@Transient
public void initialize(int levelCursor, int level)
{
    levelCursor++;

    Method[] methods = this.getClass().getMethods();

    Object obj = null;

    try
    {
        for (Method method : methods)
        {
            if (method.getAnnotation(JoinColumn.class) != null || method.getAnnotation(JoinTable.class) != null || method.getAnnotation(OneToMany.class) != null)
            {
                Object result = method.invoke(this, new Object[0]);
                if (result == null)
                    continue;

                if (result instanceof SuperEntity)
                {
                    if (levelCursor < level)
                        ((SuperEntity)result).initialize(levelCursor, level);
                } else if (result instanceof Collection)
                    initialize((Collection)result, levelCursor, level);
            }
        }
    }
    catch (Exception exc)
    {
        exc.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:1)

所以,据我了解你的任务,你想在检索它们时初始化你的实体集合的对象吗?

当您致电时,Doctrine会自动加载您的收藏。

所以你可以用吸气剂来做到这一点:

    class User
    {

        /**
         * OneToMany(targetEntity="Car", mappedBy="owner")
         */
        private $ownedCars;

        public function __construct()
        {
            $this->ownedCars = new ArrayCollection();
        }

        public function getOwnedCars($level)
        {
            // autoload collection
            foreach($this->ownedCars as $ownedCar)
            {
                $ownedCar->initialize($level);
            }

            return $this->ownedCars;
        }
    }