2
我正在嘗試爲帖子添加一個頁面查看計數器,這是用戶查看次數最多的頁面。我在Post實體中添加了一個屬性$ viewCount,它是一個整數。Symfony2 - 頁面瀏覽計數器
我希望每次用戶點擊某個特定帖子的展示頁面時都會對此進行計數。
要逐步完成這個過程,我需要設置一個計數器,每次查看時加一個+1,將其存儲在數據庫中,查詢這個數據然後將其傳遞給Twig。
的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 %}
他還需要執行表/行鎖定,或者他不能保證增量 –
@jperovic你如何執行表/行鎖定的正確性? – marty
由於您使用的教義,有關於此的一篇文章:http://docs.doctrine-project.org/en/2.0.x/reference/transactions-and-concurrency.html –