farzai/thai-slug 问题修复 & 功能扩展

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

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

farzai/thai-slug

Composer 安装命令:

composer require farzai/thai-slug

包简介

The Thai text to URL-safe slug converter with multiple transliteration strategies

README 文档

README

Latest Version on Packagist Tests Total Downloads PHP Version Require

A modern, high-performance PHP library for generating URL-friendly slugs from Thai text with multiple transliteration strategies.

🚀 Features

  • Multiple Transliteration Strategies: Phonetic, Royal Thai (RTGS), and Custom rule-based
  • High Performance: Optimized for fast processing of Thai text
  • UTF-8 Safe: Proper Thai Unicode normalization and character handling
  • Framework Agnostic: Works with any PHP framework or standalone

📋 Requirements

  • PHP 8.4 or higher
  • mbstring extension (required)
  • intl extension (required)
  • iconv extension (required)

📦 Installation

You can install the package via Composer:

composer require farzai/thai-slug

🔥 Quick Start

Basic Usage

use Farzai\ThaiSlug\ThaiSlug;

// Simple slug generation
$slug = ThaiSlug::make('สวัสดีชาวโลก');
// Output: "sawasdee-chao-lok"

$slug = ThaiSlug::make('ภาษาไทยสำหรับการพัฒนา');
// Output: "phasa-thai-samrap-kan-phattana"

Advanced Configuration

use Farzai\ThaiSlug\ThaiSlug;
use Farzai\ThaiSlug\Enums\Strategy;

$thaiSlug = new ThaiSlug();

// Using the fluent builder interface
$slug = $thaiSlug->builder()
    ->text('เทคโนโลยีและนวัตกรรม')
    ->strategy(Strategy::ROYAL)    // Use Royal Thai transliteration (RTGS)
    ->maxLength(50)                // Limit slug length
    ->separator('_')               // Use underscore separator
    ->build();

// Output: "theknoloyi_lae_nawatkam"

💡 Transliteration Strategies

1. Phonetic Strategy (Default)

Converts Thai text to phonetically similar Latin characters:

use Farzai\ThaiSlug\Enums\Strategy;

$slug = ThaiSlug::make('กรุงเทพมหานคร'); 
// Output: "krung-thep-maha-nakhon"

$thaiSlug->builder()
    ->text('โปรแกรมเมอร์')
    ->strategy(Strategy::PHONETIC)
    ->build();
// Output: "program-mer"

2. Royal Thai Strategy (RTGS)

Follows the Royal Thai General System of Transcription (official standard):

$thaiSlug->builder()
    ->text('สถาบันเทคโนโลยี')
    ->strategy(Strategy::ROYAL)
    ->build();
// Output: "sathaban-theknoloyi"

3. Custom Strategy

Define your own transliteration rules:

use Farzai\ThaiSlug\Enums\Strategy;

$thaiSlug->builder()
    ->text('ไอทีและเทคโนโลยี')
    ->strategy(Strategy::CUSTOM)
    ->strategyOptions([
        'rules' => [
            'ไอที' => 'IT',
            'เทค' => 'tech',
        ]
    ])
    ->build();
// Output: "IT-lae-tech-noloyi"

⚡ Performance

The library is optimized for high performance with Thai text processing:

  • Fast Processing: Optimized algorithms for Thai text transliteration
  • Memory Efficient: Minimal memory footprint for typical use cases
  • Modern PHP: Built with PHP 8.4+ features for optimal performance

Performance Characteristics

Text Size Typical Processing Time Memory Usage
Small (<100 chars) < 1ms < 1MB
Medium (100-1K chars) < 5ms < 2MB
Large (1K+ chars) < 50ms < 5MB

🔧 Configuration Options

Slug Builder Options

The fluent builder interface provides the following configuration options:

use Farzai\ThaiSlug\Enums\Strategy;

$slug = $thaiSlug->builder()
    ->text('ข้อความภาษาไทย')           // Text to convert
    ->strategy(Strategy::PHONETIC)      // Transliteration strategy
    ->maxLength(100)                    // Maximum slug length
    ->separator('-')                    // Separator character
    ->lowercase(true)                   // Convert to lowercase
    ->removeDuplicates(true)            // Remove duplicate separators
    ->trimSeparators(true)              // Remove leading/trailing separators
    ->strategyOptions([])               // Additional strategy-specific options
    ->build();

Available Strategies

  • Strategy::PHONETIC - Default phonetic transliteration
  • Strategy::ROYAL - Royal Thai General System (RTGS)
  • Strategy::CUSTOM - Custom transliteration rules

🧪 Testing

Run the test suite and code quality tools:

# Run all tests
composer test

# Run tests with coverage
composer test-coverage

# Run tests with HTML coverage report
composer test-coverage-html

# Code analysis with PHPStan
composer analyse

# Format code with Laravel Pint
composer format

# Check code formatting
composer format-check

# Run all quality checks
composer check-code

# Complete CI pipeline
composer ci

📊 Real-World Examples

Blog Post Slugs

$titles = [
    'วิธีการเขียนโค้ด PHP ที่มีประสิทธิภาพ',
    'เทคนิคการออกแบบฐานข้อมูลที่ดี',
    'การใช้ Laravel สำหรับโปรเจคใหญ่',
];

foreach ($titles as $title) {
    $slug = ThaiSlug::make($title);
    echo "Title: $title\n";
    echo "Slug: $slug\n\n";
}

// Output:
// Title: วิธีการเขียนโค้ด PHP ที่มีประสิทธิภาพ
// Slug: withee-kan-khian-kho-php-thee-mee-prasitthiphap

// Title: เทคนิคการออกแบบฐานข้อมูลที่ดี
// Slug: theknit-kan-ok-baep-than-kho-mul-thee-dee

// Title: การใช้ Laravel สำหรับโปรเจคใหญ่
// Slug: kan-chai-laravel-samrap-project-yai

E-commerce Product Names

$products = [
    'เสื้อยืดผู้ชาย สีน้ำเงิน ไซส์ L',
    'กระเป๋าหนังแท้ สำหรับผู้หญิง',
    'รองเท้าผ้าใบ Nike Air Max',
];

$thaiSlug = new ThaiSlug();

foreach ($products as $product) {
    $slug = $thaiSlug->builder()
        ->text($product)
        ->maxLength(60)
        ->build();
    
    echo "Product: $product\n";
    echo "Slug: $slug\n\n";
}

URL Generation in Frameworks

Laravel Integration

// In a Laravel controller
use Farzai\ThaiSlug\ThaiSlug;

class ArticleController extends Controller
{
    public function store(Request $request)
    {
        $slug = ThaiSlug::make($request->input('title'));
        
        Article::create([
            'title' => $request->input('title'),
            'slug' => $slug,
            'content' => $request->input('content'),
        ]);
        
        return redirect()->route('articles.show', ['slug' => $slug]);
    }
}

WordPress Plugin Usage

// WordPress hook
add_filter('wp_unique_post_slug', function ($slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug) {
    if ($post_type === 'post' && preg_match('/[\u{0E00}-\u{0E7F}]/u', $original_slug)) {
        return \Farzai\ThaiSlug\ThaiSlug::make($original_slug);
    }
    return $slug;
}, 10, 6);

🛡️ Security & Best Practices

Input Validation

use Farzai\ThaiSlug\Exceptions\InvalidArgumentException;

try {
    // The library automatically validates and sanitizes input
    $slug = ThaiSlug::make($userInput);
} catch (InvalidArgumentException $e) {
    // Handle invalid input gracefully
    $slug = 'default-slug';
}

Production Best Practices

use Farzai\ThaiSlug\ThaiSlug;
use Farzai\ThaiSlug\Enums\Strategy;

// Production setup with consistent configuration
$thaiSlug = new ThaiSlug(Strategy::PHONETIC);

// Process user content with validation
$slug = $thaiSlug->builder()
    ->text($userContent)
    ->maxLength(100)
    ->separator('-')
    ->lowercase(true)
    ->build();

🔄 Migration Guide

From Other Libraries

If you're migrating from other Thai slug libraries:

// Old library
$slug = some_old_thai_slug_function('ข้อความไทย');

// New library
$slug = \Farzai\ThaiSlug\ThaiSlug::make('ข้อความไทย');

🤝 Contributing

We welcome contributions! Please follow these guidelines:

Development Setup

# Clone the repository
git clone https://github.com/parsilver/thai-slug-php.git

# Install dependencies
composer install

# Run tests
composer test

# Run code analysis
composer analyse

# Format code
composer format

📝 Changelog

Please see CHANGELOG.md for more information on what has changed recently.

🔒 Security

If you discover any security-related issues, please email parkorn@farzai.com instead of using the issue tracker.

📄 License

The MIT License (MIT). Please see License File for more information.

🎯 Performance Tips

  1. Choose appropriate strategy based on your needs:
    • Phonetic: Best for readability and general use
    • Royal: Best for official/academic use (RTGS compliant)
    • Custom: Best for specialized terminology or domain-specific rules
  2. Set reasonable length limits using maxLength() to prevent overly long slugs
  3. Batch operations when processing multiple texts to reduce overhead
  4. Use consistent configuration across your application for predictable results

🙏 Credits

Built with ❤️ for the Thai developer community.

farzai/thai-slug 适用场景与选型建议

farzai/thai-slug 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 124 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 09 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 farzai/thai-slug 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-09-06