ユーザーが最も閲覧している投稿のページビューカウンターを追加しようとしています。Post エンティティに整数であるプロパティ $viewCount を追加しました。
ユーザーが特定の投稿の表示ページをクリックするたびに、これをカウントしたいと考えています。
プロセスを進めるには、カウンターを設定し、表示されるたびに +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 %}