承接 baraja-core/selectbox-tree 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

baraja-core/selectbox-tree

Composer 安装命令:

composer require baraja-core/selectbox-tree

包简介

Simple tree builder to plain selectbox array.

README 文档

README

Simple and elegant tree builder that transforms hierarchical data structures into flat selectbox-friendly arrays with visual indentation.

Sample selectbox view

✨ Key Features

  • Transforms parent-child tree structures into flat arrays suitable for HTML <select> elements
  • Automatic visual indentation using pipe characters (|) and non-breaking spaces to represent hierarchy depth
  • Built-in SQL query builder helper for fetching hierarchical data from databases
  • Configurable maximum depth to prevent infinite recursion
  • Custom name formatting through the NameFormatter interface
  • Optional integration with Baraja\Localization\Translation for multilingual support
  • Supports both raw array input and typed SelectboxItem objects
  • Zero external dependencies (PHP 8.0+ only)

🏗️ Architecture

The library consists of three main components:

┌─────────────────────────────────────────────────────────────┐
│                      SelectboxTree                          │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  process(array $data): array                        │   │
│  │  - Accepts SelectboxItem[] or raw arrays            │   │
│  │  - Builds hierarchical structure                    │   │
│  │  - Returns flat array with visual indentation       │   │
│  └─────────────────────────────────────────────────────┘   │
│                           │                                 │
│                           ▼                                 │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  serializeCategoriesToSelectbox()                   │   │
│  │  - Recursive tree traversal                         │   │
│  │  - Tracks used IDs to prevent duplicates            │   │
│  │  - Respects maxDepth limit                          │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘
           │                               │
           ▼                               ▼
┌─────────────────────┐       ┌─────────────────────────┐
│   SelectboxItem     │       │    NameFormatter        │
│  ┌───────────────┐  │       │      (interface)        │
│  │ id            │  │       │  ┌───────────────────┐  │
│  │ name          │  │       │  │ format(string):   │  │
│  │ parentId      │  │       │  │   string          │  │
│  └───────────────┘  │       │  └───────────────────┘  │
└─────────────────────┘       └─────────────────────────┘

🧩 Components Overview

Component Type Description
SelectboxTree Class Main processor that converts tree data to selectbox array
SelectboxItem Class Immutable value object representing a single tree node
NameFormatter Interface Contract for custom name transformation logic

⚙️ How It Works

Tree Transformation Process

The library takes hierarchical data where each item has an id, name, and optional parent_id, then:

  1. Normalizes input - Accepts either SelectboxItem objects or raw associative arrays
  2. Applies name formatting - If a NameFormatter is set, transforms each item's name
  3. Builds tree recursively - Starting from root items (where parent_id is null), traverses children depth-first
  4. Generates visual indentation - Prepends pipe characters and non-breaking spaces based on depth level
  5. Returns flat array - Keys are item IDs, values are formatted names with indentation

Visual Indentation Format

Each level of depth adds the pattern | (pipe followed by three non-breaking spaces):

Root Item
|   First Level Child
|   |   Second Level Child
|   |   |   Third Level Child

Input Data Format

The process() method accepts an array of items in two formats:

Array format:

[
    ['id' => 1, 'name' => 'Electronics', 'parent_id' => null],
    ['id' => 2, 'name' => 'Phones', 'parent_id' => 1],
    ['id' => 3, 'name' => 'iPhone', 'parent_id' => 2],
]

SelectboxItem format:

[
    new SelectboxItem(1, 'Electronics', null),
    new SelectboxItem(2, 'Phones', 1),
    new SelectboxItem(3, 'iPhone', 2),
]

Output Format

The process() method returns an associative array where:

  • Keys are the original item IDs (int|string)
  • Values are the formatted names with visual indentation (string)
[
    1 => 'Electronics',
    2 => '|   Phones',
    3 => '|   |   iPhone',
]

📦 Installation

It's best to use Composer for installation, and you can also find the package on Packagist and GitHub.

To install, simply use the command:

$ composer require baraja-core/selectbox-tree

You can use the package manually by creating an instance of the internal classes, or register a DIC extension to link the services directly to the Nette Framework.

Requirements

  • PHP 8.0 or higher

🚀 Basic Usage

Simple Example

use Baraja\SelectboxTree\SelectboxTree;

$tree = new SelectboxTree();

$data = [
    ['id' => 1, 'name' => 'Main category', 'parent_id' => null],
    ['id' => 2, 'name' => 'Phone', 'parent_id' => 1],
    ['id' => 3, 'name' => 'iPhone', 'parent_id' => 2],
    ['id' => 4, 'name' => 'Computer', 'parent_id' => 1],
    ['id' => 5, 'name' => 'Mac', 'parent_id' => 4],
    ['id' => 6, 'name' => 'MacBook', 'parent_id' => 5],
    ['id' => 7, 'name' => 'iMac', 'parent_id' => 5],
    ['id' => 8, 'name' => 'Windows', 'parent_id' => 4],
];

$selectboxOptions = $tree->process($data);

// Result:
// [
//     1 => 'Main category',
//     2 => '|   Phone',
//     3 => '|   |   iPhone',
//     4 => '|   Computer',
//     5 => '|   |   Mac',
//     6 => '|   |   |   MacBook',
//     7 => '|   |   |   iMac',
//     8 => '|   |   Windows',
// ]

Using with HTML Select Element

use Baraja\SelectboxTree\SelectboxTree;

$tree = new SelectboxTree();
$options = $tree->process($categories);

echo '<select name="category">';
foreach ($options as $id => $name) {
    echo sprintf('<option value="%s">%s</option>', $id, htmlspecialchars($name));
}
echo '</select>';

Using SelectboxItem Objects

use Baraja\SelectboxTree\SelectboxTree;
use Baraja\SelectboxTree\SelectboxItem;

$tree = new SelectboxTree();

$items = [
    new SelectboxItem(1, 'Electronics', null),
    new SelectboxItem(2, 'Phones', 1),
    new SelectboxItem(3, 'Computers', 1),
];

$selectboxOptions = $tree->process($items);

🔧 Advanced Configuration

Setting Maximum Depth

To prevent infinite recursion or limit the tree depth, use setMaxDepth():

$tree = new SelectboxTree();
$tree->setMaxDepth(5); // Limit to 5 levels deep

$options = $tree->process($data);

Constraints:

  • Minimum value: 1
  • Maximum value: 1000
  • Default value: 32

Custom Name Formatting

Implement the NameFormatter interface to transform item names:

use Baraja\SelectboxTree\SelectboxTree;
use Baraja\SelectboxTree\NameFormatter;

class UppercaseFormatter implements NameFormatter
{
    public function format(string $name): string
    {
        return strtoupper($name);
    }
}

$tree = new SelectboxTree();
$tree->setNameFormatter(new UppercaseFormatter());

$options = $tree->process($data);
// All names will be uppercase

SQL Query Builder

The library includes a helper method to generate SQL queries for fetching hierarchical data:

$tree = new SelectboxTree();

// Basic usage
$sql = $tree->sqlBuilder('categories');
// SELECT `id`, `name`, `parent_id` FROM `categories` ORDER BY `name` ASC

// Custom columns
$sql = $tree->sqlBuilder(
    table: 'products',
    primaryCol: 'title',
    parentCol: 'category_id',
);
// SELECT `id`, `title`, `category_id` FROM `products` ORDER BY `title` ASC

// With WHERE conditions
$sql = $tree->sqlBuilder(
    table: 'categories',
    wheres: ['active = 1', 'deleted_at IS NULL'],
);
// SELECT `id`, `name`, `parent_id` FROM `categories`
// WHERE (active = 1) AND (deleted_at IS NULL) ORDER BY `name` ASC

// Custom ORDER BY
$sql = $tree->sqlBuilder(
    table: 'categories',
    orderCol: 'position',
);
// SELECT `id`, `name`, `parent_id` FROM `categories` ORDER BY `position` ASC

Parameters:

Parameter Type Default Description
$table string required Database table name
$primaryCol string 'name' Column containing the display name
$parentCol string 'parent_id' Column containing the parent reference
$wheres array [] Array of WHERE conditions
$orderCol ?string null Column for ORDER BY (defaults to $primaryCol)

Integration with Database

use Baraja\SelectboxTree\SelectboxTree;

$tree = new SelectboxTree();

// Generate SQL query
$sql = $tree->sqlBuilder('categories', 'name', 'parent_id', ['active = 1']);

// Fetch data from database (using your preferred method)
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
$stmt = $pdo->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Process into selectbox format
$options = $tree->process($data);

🌐 Localization Support

The library automatically integrates with Baraja\Localization\Translation if available. Names starting with T:{ pattern are automatically translated:

$data = [
    ['id' => 1, 'name' => 'T:{"cs":"Kategorie","en":"Category"}', 'parent_id' => null],
];

$tree = new SelectboxTree();
$options = $tree->process($data);
// The name will be automatically translated based on current locale

This feature is optional and only activates when the baraja-core/localization package is installed.

🛡️ Safety Features

Duplicate Prevention

The library tracks processed IDs to prevent duplicate entries in the output, even if the same item appears multiple times in the input data.

Infinite Recursion Protection

Two mechanisms prevent infinite loops:

  1. Max depth limit - Configurable via setMaxDepth(), defaults to 32 levels
  2. Used ID tracking - Items are only processed once, preventing circular references

Input Validation

  • Max depth must be between 1 and 1000
  • Empty or null input arrays are handled gracefully (return empty array)

👥 Author

Jan Barasek https://baraja.cz

📄 License

baraja-core/selectbox-tree is licensed under the MIT license. See the LICENSE file for more details.

baraja-core/selectbox-tree 适用场景与选型建议

baraja-core/selectbox-tree 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 66.5k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2020 年 07 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 66.5k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 4
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: Unknown
  • 更新时间: 2020-07-14