positibe / unique-views-bundle
Symfony PositibeUniqueViewsBundle 用于计算对象模型的浏览次数
1.2.0
2018-12-02 01:38 UTC
Requires
- symfony/framework-bundle: ^3.4||^4.0
This package is not auto-updated.
Last update: 2024-09-28 18:34:46 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 implements 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);