【发布时间】:2014-08-12 11:21:17
【问题描述】:
我正在尝试为用户查看次数最多的帖子添加页面查看计数器。我在我的 Post 实体中添加了一个属性 $viewCount,它是一个整数。
我希望每次用户点击特定帖子的显示页面时都会计算此值。
要逐步完成该过程,我需要设置一个计数器,每次查看时添加一个 +1,将其存储在数据库中,查询它然后将其传回给 Twig。
搜索了hrs后不知道怎么做的2个部分是:
1) 每次用户查看页面时如何添加(我知道你想以某种方式使用 +1)
2)如何查询最多的页面浏览量以传递给控制器和树枝
showAction
/**
* Show Post
*
* @param $slug
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
* @return array
*
* @Route("/post/{slug}", name="acme_demo_show")
* @Template("AcmeDemoBundle:Page:show.html.twig")
*/
public function showPostAction($slug)
{
$article = $this->getDoctrine()->getRepository('AcmeBundle:Post')
->findOneBy(array(
'slug' => $slug
));
if (null === $article) {
throw $this->createNotFoundException('Post was not found');
}
// Increment views each time user clicks on an article
$em = $this->getDoctrine()->getManager();
$views = $article->getViews();
$article->setViews($views + 1);
$em->flush();
return array(
'article' => $article,
);
}
侧边栏操作
public function sidebarAction()
{
$em = $this->getDoctrine()->getManager();
$post = $em->getRepository('AcmeDemoBundle:Article')
->getMostRecentArticles(5);
if (!$post) {
throw $this->createNotFoundException('No posts were found');
}
$articles = $this->getDoctrine()->getRepository('AcmeDemoBundle:Article')
->findBy(array(
array(
'views' => 'ASC'
)
));
return array(
'post' => $post,
'articles' => $articles
);
}
树枝
<h3>Most Popular Articles</h3>
{% for article in articles %}
<a href="{{ path('acme_demo_article_show', { slug: article.slug }) }}" class="anchor" style="text-decoration: none">{{ article.title }}</a><br>
{% endfor %}
【问题讨论】:
标签: symfony doctrine-orm count counter pageviews