2014-06-22 29 views
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 %} 

回答

5

如果你想,當用戶點擊你需要使用AJAX的JavaScript的鏈接,增加計數器。

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

最好的做法存在添加increment()方法您Article實體:另外,您可以用類似的東西做在你的文章的控制器純PHP。

然後,由觀點查詢文章:

$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(); 

} 
+0

他還需要執行表/行鎖定,或者他不能保證增量 –

+0

@jperovic你如何執行表/行鎖定的正確性? – marty

+1

由於您使用的教義,有關於此的一篇文章:http://docs.doctrine-project.org/en/2.0.x/reference/transactions-and-concurrency.html –