lahmacun / hit-counter-bundle
Symfony PositibeUniqueViewsBundle 用于统计对象模型的观看次数
dev-master / 1.1.x-dev
2020-03-15 20:56 UTC
Requires
- symfony/framework-bundle: ~2.8||~3.0||~4.0
This package is not auto-updated.
Last update: 2024-09-24 16:55:50 UTC
README
这个包允许你为你可访问的实体添加计数系统。
安装
要安装这个包,只需添加依赖包
php composer.phar require positibe/media-bundle
接下来,确保在你的应用程序内核中启用这些包
<?php
// app/AppKernel.php
public function registerBundles()
{
return array(
// ...
new Positibe\Bundle\UniqueViewsBundle\PositibeUniqueViewsBundle(),
// ...
);
}
两步文档
-
实现 VisitableInterface
// src/AppBundle/Entity/Post.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM; use Positibe\Bundle\UniqueViewsBundle\Model\VisitableInterface;
class Post implement VisitableInterface {
/** * @ORM\Column(name="count_views", type="integer") */ protected $countViews = 0; /** * @ORM\Column(name="slug", type="string", length=255) */ protected $slug; public function getSlug() { return $this->slug; } /** * {@inheritdoc} */ public function getVisitableId() { return $this->getSlug(); } /** * {@inheritdoc} */ public function getVisitableType() { return 'post'; } /** * {@inheritdoc} */ public function onNewViewed() { return $this->countViews++; } /** * {@inheritdoc} */ public function countViews() { return $this->countViews; }
}
提示:
你可以使用 AbstractVisitable
或 VisitableTrait
来最小化你的代码。
// src/AppBundle/Entity/Post.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Positibe\Bundle\UniqueViewsBundle\Model\VisitableInterface;
class Post implement VisitableInterface {
use VisitableTrait;
/**
* @ORM\Column(name="slug", type="string", length=255)
*/
protected $slug;
public function getSlug()
{
return $this->slug;
}
/**
* {@inheritdoc}
*/
public function getVisitableId()
{
return $this->getSlug();
}
}
-
在一个可计数的模板中,你可以使用
positibe_unique_views
函数来计算观看次数。{# app/Resources/views/post/show.html.twig #}
{{ post.title }}
{{ positibe_unique_views(post) }} 独特观看次数
2.1 在一个可计数的控制器中,你可以使用 positibe_unique_views.views_counter
服务来计算观看次数
//src/AppBundle/Controller/PostController
$this->get('positibe_unique_views.views_counter')->count($post);