xepozz/entity-sorter-bundle

为实体添加排序功能

安装: 11

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 1

类型:symfony-bundle

v1.0.0 2020-01-05 08:26 UTC

This package is auto-updated.

Last update: 2024-09-05 19:22:13 UTC


README

步骤 1:下载 Bundle

打开命令行控制台,进入你的项目目录,并执行以下命令以下载此 Bundle 的最新稳定版本

$ composer require xepozz/entity-sorter-bundle

此命令要求你全局安装 Composer,具体请参阅 Composer 文档中的安装章节

步骤 2:将其添加到实体中

将 Doctrine 实体监听器添加到你的实体中,并不要忘记包含所有 use 语句。然后,如以下示例所示,扩展你的实体以使用 BaseSort。

<?php
// AppBundle/Entity/OrderListItem.php

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="order_list_item")
 * @ORM\EntityListeners({"Xepozz\EntitySorterBundle\EventListener\SortListener"})
 */
class OrderListItem
{
    public function getId(){ /**/ }
    public function setId(){ /**/ }
    public function getSort(){ /**/ }
    public function setSort(){ /**/ }
    public function getSuperCategories(){ /**/ }
}

在此更改之后,排序值将自动为新数据库条目设置,并在删除或更新条目时正确修改。

步骤 3:移动项目上下

要移动你的项目在排序顺序中上下,使用实体函数 moveUp($controller)moveDown($controller)。例如,你可以在控制器中调用这些函数。你的控制器类必须扩展 Symfony 控制器

<?php
// AppBundle/Controller/testController.php

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Xepozz\EntitySorterBundle\Utils\EntitySorter;

class TestController extends Controller
{
    private $entitySorter;

    public function __construct(EntitySorter $entitySorter) 
    {
        $this->entitySorter = $entitySorter;
    }
    
    public function moveUpAction(OrderListItem $entity)
    {
        $this->entitySorter->moveUp($entity);

        return $this->redirect('...');
    }
    
    public function moveDownAction(OrderListItem $entity)
    {
        $this->entitySorter->moveDown($entity);

        return $this->redirect('...');
    }
}

(可选)步骤 4:超级类别内的排序

如果你的实体是另一个实体的子类别,并且应该在它自己的超级类别内进行排序,你需要覆盖你的实体中的 getSuperCategories() 函数。

以下示例中,我们有一个需要在其产品类别内进行排序的产品子类别。

<?php
// AppBundle/Entity/ProductSubCategory.php

use Doctrine\ORM\Mapping as ORM;use Xepozz\EntitySorterBundle\Model\BaseSort;

/**
 * @ORM\Entity
 * @ORM\Table(name="product_sub_category")
 * @ORM\EntityListeners({"Xepozz\EntitySorterBundle\EventListener\SortListener"})
 */
class ProductSubCategory extends BaseSort
{
    /**
     * @ORM\ManyToOne(targetEntity="ProductCategory", inversedBy="productSubCategories")
     * @ORM\JoinColumn(name="product_category_id", referencedColumnName="id")
     */
    protected $productCategory;

    /**
     * @return array
     */
    public function getSuperCategories()
    {
        return ['productCategory' => $this->getProductCategory()];
    }
}

实体可以有多个超级类别。在 getSuperCategories 返回的数组中,只需要包含它们的值。超级类别的顺序对排序没有影响

return [
    'productCategory' => $this->getProductCategory(),
    'anotherSuperCategory' => $this->getAnotherSuperCategory()
];