【发布时间】:2016-02-11 14:09:21
【问题描述】:
我在 Symfony2 中构建一个博客,它有两个实体:Blog 和 BlogComment(这是一个简化的示例)。 Blog 与 BlogComment 具有 OneToMany 关系。发布BlogComment 时,属性published 设置为false。管理员批准BlogComment后,设置为true。
我想用我所有的Blog-posts 创建一个概览,并在两个单独的字段中显示published = true 和published = false 的BlogComment 的数量。可以将所有 BlogComment 放在一个循环中并进行计数,但因为它可能是对 Blog-posts 的一个非常大的概述,所以这不是我的首选。
我在Blog 创建了两个属性:published_comments_count 和unpublished_comments_count。为了更新这些字段,我为BlogComment 创建了一个监听器:
class BlogCommentListener
{
public function onFlush(OnFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
$entities = array_merge(
$uow->getScheduledEntityInsertions(),
$uow->getScheduledEntityUpdates(),
$uow->getScheduledEntityDeletions()
);
foreach($entities as $entity){
if($entity instanceof BlogComment){
$Blog = $entity->getBlog();
$published_comments_count = 0;
$unpublished_comments_count = 0;
foreach($Blog->getComments() as $BlogComment){
if($BlogComment->getPublished()){
$published_comments_count++;
} else {
$unpublished_comments_count++;
}
}
$Blog->setPublishedCommentsCount($published_comments_count);
$Blog->setUnpublishedCommentsCount($unpublished_comments_count);
$em->persist($Blog);
$md = $em->getClassMetadata(get_class($Blog));
$uow->recomputeSingleEntityChangeSet($md, $Blog);
}
}
}
}
它工作得很好,但是当我添加新评论时,它还没有在$Blog->getComments() 的 ArrayCollection 中。有没有办法计算这个 ArrayCollection 的变化?
【问题讨论】:
标签: symfony caching listener counter