serj/sortable-tree 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

serj/sortable-tree

Composer 安装命令:

composer require serj/sortable-tree

包简介

A set of classes for Yii2 to create and maintain a tree.

README 文档

README

A set of classes for Yii2 to create and maintain a tree-like structure.

Installation

To import the component to your project, put the following line to the require section of your composer.json file:

"serj/sortable-tree": "~1.0.0"

or run the command

$ composer require serj/sortable-tree "~1.0.0"

To create database tables apply a migration.

./yii migrate --migrationPath=@app/vendor/serj/sortable-tree/migrations

Usage

Adding a root

Tree::addItem();

Adding a nested item

Assume that root item has an id = 1. To add an item under the root:

Tree::addItem(1);

Let's add another item, but insert it before previous one. We assume that last inserted item has id = 2.

$parent = 1;
$target = 2;
$position = 'before';
Tree::addItem($parent, $target, $position);

For the moment, our tree looks like this:

├── 1
│   ├── 3
│   └── 2

Moving items

Let's swap items 2 and 3

$parent = 1; // we move items under the same parent
$id = 3 // move this item
$target = 2; // we want to locate the item after this one
$position = 'after';
Tree::moveTo($id, $parent, $target, $position)

Now it should be like this:

├── 1
│   ├── 2
│   └── 3

Let's nest the item 3 into the item 2

$parent = 2;
$id = 3
$position = 'after';
Tree::moveTo($id, $parent)

The result is:

├── 1
│   ├── 2
│   	├── 3

Deletion

Tree::deleteRecursive(2);

We deleted item 2 and its child 3. The root item left.

├── 1

Getting the tree

Tree::getDescendingTree();

There are many other methods to work with the tree. For more information you can explore public methods of the Tree class and unit tests.

I want to store more data

Lets suppose you want to store title, created_at, updated_at fields. And you no longer want to remove items from the tree, but mark them as deleted. To achieve this, we can extend the Tree calss. But first, let's modify a migration.

class m171217_033811_sortable_tree_tables extends Migration
{
    /**
     * @inheritdoc
     */
    public function safeUp()
    {
        $this->createTable('{{%tree_data}}', [
            'id' => $this->primaryKey(),
            'parent_id' => $this->integer(),
            'level' => $this->integer(),
            'sort' => $this->integer(),
            'title' => $this->string(),
            'deleted' => $this->boolean()->defaultValue(false),
            'created_at' => $this->timestamp()->defaultValue('NOW()'),
            'updated_at' => $this->timestamp()->defaultValue('NOW()'),
            'deleted_at' => $this->timestamp(),
        ]);

        $this->createTable('{{%tree_structure}}', [
            'id' => $this->primaryKey(),
            'parent' => $this->integer(),
            'child' => $this->integer()
        ]);
    }

    /**
     * @inheritdoc
     */
    public function safeDown()
    {
        $this->dropTable('{{%tree_data}}');
        $this->dropTable('{{%tree_structure}}');
    }
}

Do not forget to apply a new migration.

Extend the tree class. Add and overwrite some methods.

<?php

use yii\db\Expression;

class TreeExtended extends \serj\sortableTree\Tree
{
    /**
     * @inheritdoc
     */
    public static function instantiate($row)
    {
        $model = new self();
        $model->setFilter(new Filter());

        return $model;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return array_merge(
            parent::rules(),
            [
                ['title', 'string'],
                ['deleted', 'boolean'],
                [['created_at', 'updated_at', 'deleted_at'], 'safe']
            ]
        );
    }

    /**
     * @param int $id
     * @return null|RecordTreeData|\yii\db\ActiveRecord
     * @throws NotFoundHttpException
     */
    public function editTitle(int $id, $title)
    {
        $model = self::getRecord($id);
        $model->setAttributes([
            'title' => $title,
            'updated_at' => new Expression('NOW()')
        ]);

        if ($model->save()) {
            $model->refresh();

            return $model;
        }

        return $model;
    }

    /**
     * @param array $ids
     * @return int
     * @throws \yii\db\Exception
     */
    protected static function deleteItems(array $ids) {
        return \Yii::$app->db->createCommand()
            ->update(
                self::tableName(),
                ['deleted' => true, 'deleted_at' => new Expression('NOW()')],
                ['id' => $ids]
            )
            ->execute();
    }
}

To skip deleted items we've added a filter in the class constructor. Let's implement it.

<?php

use yii\db\Query;

class Filter implements \serj\sortableTree\FilterInterface
{
    /**
     * @inheritdoc
     */
    public function applyFilter(Query $query)
    {
        $query->andWhere([
            'deleted' => false
        ]);

        return $query;
    }
}

Now to add an item, pass an array of extra attributes that was added to migration. In or case it's title.

TreeExtended::addItem(0, null, null , ['title' => 'Root']);

To edit a title of the existing item:

TreeExtended::editTitle(1, 'Root modified');

For deletion use the same method as above.

Tree::deleteRecursive(1);

Tree class triggers a set of events, which might be useful.

    const EVENT_AFTER_ADD = 'tree.after_add';
    const EVENT_BEFORE_MOVE = 'tree.before_move';
    const EVENT_AFTER_MOVE = 'tree.after_move';
    const EVENT_BEFORE_DELETE = 'tree.before_delete';
    const EVENT_AFTER_DELETE = 'tree.after_delete';
    const EVENT_BEFORE_TREE_QUERY = 'tree.before_tree_query';

For example to get ids of the items before they are deleted:

\Yii::$app->on(Tree::EVENT_BEFORE_DELETE, function (\serj\sortableTree\EventTree $event) {
    print_r($event->senderData['ids']);
});

Using with MySql database (by default it's Postgres)

Tree::setSortManager(
    new Sortable([
        'targetTable' => Tree::tableName(),
        'pkColumn' => 'id',
        'srtColumn' => 'sort',
        'grpColumn' => 'parent_id',
        'databaseDriver' => Sortable::DB_DRIVER_MYSQL
    ])
); 

serj/sortable-tree 适用场景与选型建议

serj/sortable-tree 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 27 次下载、GitHub Stars 达 0, 最近一次更新时间为 2017 年 12 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「yii」 「yii2」 「yii 2」 「tree structure」 「sortable tree」 「storing tree data in a atabase」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 serj/sortable-tree 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 serj/sortable-tree 我们能提供哪些服务?
定制开发 / 二次开发

基于 serj/sortable-tree 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 27
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-12-17