title: Symfony2 - Page view counter
body: <p>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.</p>
  
  <p>I want this to be counted each time the user clicks on the show page for a particular post. </p>
  
  <p>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.</p>
  
  <p><strong>The 2 parts I don't know how to do after searching for hrs, is:</strong></p>
  
  <p>1) How to add each time the user views the page (I know you want to use a +1 somehow)</p>
  
  <p>2) How to query for the most page views to pass to the controller and twig</p>
  
  <p><strong>showAction</strong></p>
  
  <pre><code>/**
   * 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-&gt;getDoctrine()-&gt;getRepository('AcmeBundle:Post')
          -&gt;findOneBy(array(
              'slug' =&gt; $slug
          ));
  
      if (null === $article) {
          throw $this-&gt;createNotFoundException('Post was not found');
      }
  
      // Increment views each time user clicks on an article
      $em = $this-&gt;getDoctrine()-&gt;getManager();
      $views = $article-&gt;getViews();
      $article-&gt;setViews($views + 1);
      $em-&gt;flush();
  
      return array(
          'article' =&gt; $article,
      );
  }
  </code></pre>
  
  <p>sidebar action</p>
  
  <pre><code>public function sidebarAction()
  {
      $em = $this-&gt;getDoctrine()-&gt;getManager();
  
      $post = $em-&gt;getRepository('AcmeDemoBundle:Article')
          -&gt;getMostRecentArticles(5);
  
      if (!$post) {
          throw $this-&gt;createNotFoundException('No posts were found');
      }
  
      $articles = $this-&gt;getDoctrine()-&gt;getRepository('AcmeDemoBundle:Article')
          -&gt;findBy(array(
              array(
                  'views' =&gt; 'ASC'
              )
          ));
  
      return array(
          'post' =&gt; $post,
          'articles' =&gt; $articles
      );
  }
  </code></pre>
  
  <p>Twig</p>
  
  <pre><code>&lt;h3&gt;Most Popular Articles&lt;/h3&gt;
      {% for article in articles %}
          &lt;a href="{{ path('acme_demo_article_show', { slug: article.slug }) }}" class="anchor" style="text-decoration: none"&gt;{{ article.title }}&lt;/a&gt;&lt;br&gt;
      {% endfor %}
  </code></pre>