I am trying to add a page view counter for posts, that are the most viewed by the user. I have added a property $viewCount which is an integer into my Post entity.
I want this to be counted each time the user clicks on the show page for a particular post.
To step through the process, I need to setup a counter, add a +1 each time it's viewed, store this in the database, query for this then pass this back out to Twig.
The 2 parts I don't know how to do after searching for hrs, is:
1) How to add each time the user views the page (I know you want to use a +1 somehow)
2) How to query for the most page views to pass to the controller and twig
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,
);
}
sidebar action
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
);
}
Twig
<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 %}