0
我們都遇到了這一問題處理:當我們試圖setFilters()
/getFilters()
如何在一個通用的方法的過濾器避免了會話存儲「實體必須是管理」
那麼如何以通用的方式處理過濾器的會話存儲,以避免merging
和detaching
或re-hydrating
手動的實體?
請參閱下面的答案。
我們都遇到了這一問題處理:當我們試圖setFilters()
/getFilters()
如何在一個通用的方法的過濾器避免了會話存儲「實體必須是管理」
那麼如何以通用的方式處理過濾器的會話存儲,以避免merging
和detaching
或re-hydrating
手動的實體?
請參閱下面的答案。
嗯,有些同事(@ 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:不要忘了添加使用ArrayCollection
免責聲明,我們不知道這是否是一種好的做法,我們知道至少有一個限制:您必須確保您嘗試保存在會話中的對象具有id
(這是99.9%的情況)