mar*_*rty 2 counter count pageviews symfony doctrine-orm
我正在尝试为帖子添加页面视图计数器,这是用户查看次数最多的.我在Post实体中添加了一个属性$ viewCount,它是一个整数.
我希望每次用户点击特定帖子的节目页面时都会对此进行计数.
要逐步完成整个过程,我需要设置一个计数器,每次查看时添加+1,将其存储在数据库中,然后查询,然后将其传回给Twig.
搜索hrs后我不知道怎么做的两部分是:
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,
);
}
Run Code Online (Sandbox Code Playgroud)
侧边栏动作
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
);
}
Run Code Online (Sandbox Code Playgroud)
枝条
<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 %}
Run Code Online (Sandbox Code Playgroud)
如果你想在用户点击链接时增加计数器,你需要使用AJAX javascript.或者你可以在你的帖子的控制器中使用纯PHP进行以下操作:
$views = $article->getViews();
$article->setViews($views + 1);
$em->persist($article);
$em->flush();
Run Code Online (Sandbox Code Playgroud)
最佳做法是向increment()您的Article实体添加方法.
然后,按视图查询文章:
$articles = $this->getDoctrine()->getRepository('AcmeBundle:Post')
->findBy(array(), array('views' => 'ASC'));
Run Code Online (Sandbox Code Playgroud)
但更好的做法是在实体的存储库中编写自己的方法.
更新:
知识库
public function getMostPopularArticles()
{
return $this->createQueryBuilder('article')
->select('article')
->orderBy('article.views', 'DESC')
->getQuery()
->execute();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3751 次 |
| 最近记录: |