yaso/entity-rating-bundle

简化symfony 4|3中的实体评分

安装: 6

依赖项: 0

建议者: 0

安全性: 0

星标: 0

关注者: 1

分支: 3

类型:symfony-bundle

2.0.2 2019-02-02 09:48 UTC

This package is auto-updated.

Last update: 2024-09-29 05:28:11 UTC


README

Rating example

安装

最简单的方式是使用Composer包管理器

composer require yaso/entity-rating-bundle

注册包

// app/AppKernel.php
public function registerBundles()
{
    $bundles = array(
        // ...
        new Yaso\Bundle\EntityRatingBundle\YasoEntityRatingBundle(),
        // ...
    );
}

导入路由

# app/config/routing.yml
yaso_entity_rating:
    resource: "@YasoEntityRatingBundle/Resources/config/routing.yml"
    prefix:   /

配置

扩展抽象实体以创建自己的

// src/Acme/AppBundle/Entity/EntityRate.php

namespace Acme\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Yaso\Bundle\EntityRatingBundle\Entity\EntityRate as BaseEntityRate;

/**
 * EntityRate
 * @ORM\Table(name="entity_rate")
 * @ORM\Entity(repositoryClass="Yaso\Bundle\EntityRatingBundle\Repository\EntityRateRepository")
 */
class EntityRate extends BaseEntityRate
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @return mixed
     */
    public function getId(): int
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }
}

在实体类中添加注解

# src/Acme/AppBundle/Entity/Post.php

use Yaso\Bundle\EntityRatingBundle\Annotation\Rated;
...

/**
 * Post
 * @ORM\Table(name="post")
 * ...
 * @Rated(min=1, max=5, step=1)
 * ...
 */

配置包

# app/config/config.yml
yaso_entity_rating:
     # Your EntityRate namespace, persisted in the DB (according to the namespace of the entity previously created)
     entity_rating_class: Acme\AppBundle\Entity\EntityRate
     # If you decide to extend the default manager, put the service name here
     entity_rating_manager_service: acme.entity_rating.manager
     # Maximum number of rate allowed by IP for a given entity
     rate_by_ip_limitation: 10
     # Map the alias used in frontend and the corresponding class
     map_type_to_class:
       post: Acme\AppBundle\Entity\Post
       # If you need several rated entity, just add them here 
       article: Acme\AppBundle\Entity\Article 

# In order to print the Rating field, pass the template of the field to twig       
twig:
    form_themes:
        - "YasoEntityRatingBundle:form:fields.html.twig"

在控制器中生成评分表单

$entityRatingManager = $this->get('yaso.entity_rating_bundle.manager');
$ratingForm          = $entityRatingManager->generateForm(Post::RATING_ALIAS, $post->getId());
$globalRateData      = $entityRatingManager->getGlobalRateData($post->getId(), Post::RATING_ALIAS);

/** @var EntityRate $rate */
if ($rate = $entityRatingManager->getUserCurrentRate($post->getId(), Post::RATING_ALIAS)) {
    $ratingForm->get('rate')->setData($rate->getRate());
}

return $this->render(
    '@AcmeApp/Blog/show.html.twig',
    [
        'ratingForm'       => $ratingForm->createView(),
        'globalRateData'   => $globalRateData,
    ]
);

在视图中显示表单

{% include 'YasoEntityRatingBundle::ratingWidget.html.twig' with {'form':ratingForm, 'globalRateData':globalRateData} only %}

导入资源

您可以直接导入它们

JS

<script src="{{ asset('bundles/yasoentityrating/js/entityRating.js') }}"></script>

CSS

<link rel="stylesheet" href="{{ asset('bundles/yasoentityrating/css/entityRating.css') }}" type="text/css" media="screen">

或者使用任务管理器(gulp/grunt...)在提供服务之前压缩/合并/丑化它们。

初始化JS

new EntityRating({
    form             : $('.entityrating-form'),
    radioButtonClass : '.star-rating-item',
    successCallback  : function (response) {
        var ratingWidgetSelector = $('.entity-rating-widget-wrapper[data-entity-rating-id="' + response.entityRatingId + '"]');
        ratingWidgetSelector.find('.entity-rating-rate-container').slideDown();
        ratingWidgetSelector.find('*[itemprop="ratingCount"]').text(response.rateData.rateCount);
        ratingWidgetSelector.find('*[itemprop="ratingValue"]').text(response.rateData.averageRate);
    },
    errorCallback    : function (response) {
        // Do something in case of error
    }
});

高级用法

向评分实体添加关系

示例: 在评分实体中保存登录用户

  1. 将用户字段添加到实体
 /**
  * @var User
  * @ORM\ManyToOne(targetEntity="Acme\AppBundle\Entity\User")
  * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
  */
 protected $user;
    
 /**
  * @return User
  */
 public function getUser(): User
 {
   return $this->user;
 }

 /**
  * @param User $user
  */
 public function setUser(User $user)
 {
     $this->user = $user;
 }
  1. 扩展默认管理器以处理用户
namespace Acme\AppBundle\Manager;

use Yaso\Bundle\EntityRatingBundle\Entity\EntityRateInterface;
use Yaso\Bundle\EntityRatingBundle\Factory\EntityRatingFormFactory;
use Yaso\Bundle\EntityRatingBundle\Manager\EntityRatingManager as BaseEntityRatingManager;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\ORM\EntityManager;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

class EntityRatingManager extends BaseEntityRatingManager
{

    private $user = null;

    public function __construct(
        AnnotationReader $annotationReader,
        EntityRatingFormFactory $formFactory,
        EventDispatcherInterface $eventDispatcher,
        EntityManager $entityManager,
        $entityRatingClass,
        $mapTypeToClass,
        $rateByIpLimitation,
        TokenStorage $tokenStorage
        ){
        parent::__construct($annotationReader, $formFactory, $eventDispatcher, $entityManager, $entityRatingClass, $mapTypeToClass, $rateByIpLimitation);

        /** @var TokenInterface $token */
        $token = $tokenStorage->getToken();
        if ($token !== null && is_object($token->getUser())) {
            $this->user = $token->getUser();
        }
    }

    public function getUserCurrentRate($entityId, $entityType, $ignoreFields = [])
    {
        if ($this->user) {
            return $this->entityRateRepository->findOneBy(
                [
                    'entityId'   => $entityId,
                    'entityType' => $entityType,
                    'user'       => $this->user,
                ]
            );
        } else {
            return parent::getUserCurrentRate($entityId, $entityType, ['user']);
        }
    }

    /**
     * @param \Acme\AppBundle\Entity\EntityRate|EntityRateInterface $rate
     * @param $entityId
     * @param $entityType
     * @param $rateValue
     *
     * @return \Acme\AppBundle\Entity\EntityRate|EntityRateInterface
     */
    protected function hydrateEntity(EntityRateInterface $rate, $entityId, $entityType, $rateValue)
    {
        if ($this->user) {
            $rate->setUser($this->user);
        }
        parent::hydrateEntity($rate, $entityId, $entityType, $rateValue);

        return $rate;
    }
}
  1. 定义一个新的管理器服务以在控制器中使用
acme.entity_rating.manager:
    class: Acme\AppBundle\Manager\EntityRatingManager
    parent: yaso.entity_rating_bundle.manager
    arguments: ['@security.token_storage']

事件

当评分被创建时,包会派发事件

  • 创建: yaso.entity_rating.rate_created
  • 更新: yaso.entity_rating.rate_updated