0

私たちは皆、その問題に直面してきました:「エンティティは管理されなければならないsetFilters()/getFilters()

mergingでは、エンティティを回避detachingまたはre-hydrating手動で行うために、フィルターのセッション ストレージを一般的な方法で処理するにはどうすればよいでしょうか。

すぐ下の答えを参照してください。

4

1 に答える 1

1

さて、職場の同僚 (@benji07) が次のように書いています。

/**
 * Set filters
 * @param string $name    Name of the key to store filters
 * @param array  $filters Filters
 */
public function setFilters($name, array $filters = array())
{
    foreach ($filters as $key => $value) {
        // Transform entities objects into a pair of class/id
        if (is_object($value)) {
            if ($value instanceof ArrayCollection) {
                if (count($value)) {
                    $filters[$key] = array(
                        'class' => get_class($value->first()),
                        'ids' => array()
                    );
                    foreach ($value as $v) {
                        $identifier = $this->getDoctrine()->getEntityManager()->getUnitOfWork()->getEntityIdentifier($v);
                        $filters[$key]['ids'][] = $identifier['id'];
                    }
                }
            }
            elseif (!$value instanceof \DateTime) {
                $filters[$key] = array(
                    'class' => get_class($value),
                    'id'    => $this->getDoctrine()->getEntityManager()->getUnitOfWork()->getEntityIdentifier($value)
                );
            }
        }
    }

    $this->getRequest()->getSession()->set(
        $name,
        $filters
    );
}

/**
 * Get Filters
 * @param string $name    Name of the key to get filters
 * @param array  $filters Filters
 *
 * @return array
 */
public function getFilters($name, array $filters = array())
{
    $filters = array_merge(
        $this->getRequest()->getSession()->get(
            $name,
            array()
        ),
        $filters
    );

    foreach ($filters as $key => $value) {
        // Get entities from pair of class/id
        if (is_array($value) && isset($value['class']) && isset($value['id'])) {
            $filters[$key] = $this->getDoctrine()->getEntityManager()->find($value['class'], $value['id']);
        } elseif (isset($value['ids'])) {
            $data = $this->getDoctrine()->getEntityManager()->getRepository($value['class'])->findBy(array('id' => $value['ids']));
            $filters[$key] = new ArrayCollection($data);
        }
    }

    return $filters;
}

基本的なエンティティと多値の選択肢で機能します

PS: use ステートメントを追加することを忘れないでくださいArrayCollection

免責事項、それが良い習慣であるかどうかはわかりません。また、少なくとも 1 つの制限があることもわかっています。セッションで保存しようとするオブジェクトには、id(99.9% の場合です)

于 2012-06-12T07:47:27.177 に答える