3

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 %}
4

1 回答 1

7

如果您想在用户单击链接时增加计数器,则需要带有 AJAX 的 javascript。或者,您可以在您的帖子控制器中使用纯 php 执行此操作,例如:

$views = $article->getViews();
$article->setViews($views + 1);
$em->persist($article);
$em->flush();

increment()向您的Article实体添加方法的最佳实践。

然后,按视图查询文章:

 $articles = $this->getDoctrine()->getRepository('AcmeBundle:Post')
        ->findBy(array(), array('views' => 'ASC'));

但更好的做法是在实体的存储库中编写您自己的方法。

更新:

存储库

public function getMostPopularArticles()
{
    return $this->createQueryBuilder('article')
        ->select('article')
        ->orderBy('article.views', 'DESC')
        ->getQuery()
        ->execute();

}
于 2014-06-22T07:20:32.757 回答