定制 hadi-aghandeh/laravel-friendly-id 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

hadi-aghandeh/laravel-friendly-id

Composer 安装命令:

composer require hadi-aghandeh/laravel-friendly-id

包简介

map integer id to a friendly string

README 文档

README

Laravel Friendly ID - Laravel String ID

Looking to convert the integer primary ID of your laravel model to an user friendly string?

This package enables you to generate string-based IDs for your models, without the need for a separate ID column. By default, Laravel uses integer IDs with MySQL, but in many cases, you may need unique string identifiers for your models. This package helps you implement these unique string IDs seamlessly.

1335684976 -> encode -> xxx-xxxx-xxx -> decode -> 1335684976

Here are some potential uses for having a string representation of IDs:

  • URL Creation: A string representation of integer IDs can enhance your application's readability by masking real IDs and improving clarity, especially in URLs. Such as Google Meet style urls
  • Model Tracking: You can use string IDs instead of integers for better user experience.
  • Reference Codes: For customer-facing references, like invoices or orders, string IDs are more user-friendly than raw numbers.
  • API Responses: String-based IDs can make API data less predictable and easier to manage across different systems.
  • Cross-System Compatibility: Some external systems may require a string format for identifiers, and strings can offer better flexibility for integration.

Laravel Friendly ID is easy to use:

// use the trait
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use HadiAghandeh\FriendlyId\Traits\FriendlyId;

class Post extends Model
{
    use FriendlyId;
}

// get encoded id
$post = Post::find(1);
$friendlyId = $post->friendly_id // = xxx-xxxx-xxx

// find the model
$post = Post::whereFriendlyId($friendlyId);

Installation

Install the package via Composer:

composer require hadi-aghandeh/laravel-friendly-id

Configuration

After installing the package, publish the configuration file:

php artisan vendor:publish --tag="friendly-id"

This will create a config/friendly-id.php file where you can customize the encoding settings.

Default Configuration

return [
 /*
     |--------------------------------------------------------------------------
     | Alphabets
     |--------------------------------------------------------------------------
     |
     | provide a alphabet string it is best if you provide a string with randomized order
     |
     */
    'alphabet' => env('FRIENDLY_ID_ALPHABET', "abcdefghijklmnopqrstuvwxyz"),

    /*
     |--------------------------------------------------------------------------
     | Encoder Name
     |--------------------------------------------------------------------------
     |
     | available option BASEN, SQIDS and WORDS
     |
     */
    'encoder' => env('FRIENDLY_ID_ENCODER', 'SQIDS'),

    /*
     |--------------------------------------------------------------------------
     | Minimum length
     |--------------------------------------------------------------------------
     |
     | This option controls the minimum length of the encoded string
     |
     */
    'length' => env('FRIENDLY_ID_LENGTH', 10),

    /*
     |--------------------------------------------------------------------------
     | Default column
     |--------------------------------------------------------------------------
     |
     | This option controls the default column that friendly id uses
     |
     */
    'column' => env('FRIENDLY_ID_COLUMN', 'id'),
];
  • alphabet: The set of characters used to encode the ID. By default, it uses "abcdefghijklmnopqrstu". You can modify it via environment variables.
  • encoder: The encoder algorithm used to create friendly IDs. The default encoder is "SQIDS". You can change this through the FRIENDLY_ID_ENCODER environment variable. available encoders are BASEN and SQIDS

Encoders

BASEN

This changes the base of the integer to letters provided by FRIENDLY_ID_ALPHABET.

Example output with a length of 7:

124 -> ctt-rctz 
125 -> ctt-rcty
50000 -> ctt-tyrj
50001 -> ctt-tyri
50002 -> ctt-tyrh
100000 -> ctt-pfwd
100001 -> ctt-pfwc
100002 -> ctt-pfwb
1000000 -> ctv-oodv
1000000000 -> ndh-nmh
1000000001 -> ndh-nmg

SQIDS

This uses the well-known Sqids algorithm with its PHP package.

Example output with a length of 10:

100002 -> esz-xmrs-alo 
1000000 -> msw-pppt-ozp 
1000000000 -> uyr-vkkk-kgq
1000000001 -> gmx-qeee-rkr
1000000002 -> mqs-dppp-sto
1256541245 -> vdb-ryev-tqc
1000000000000 -> mzj-rppp-ppp
12545656455156 -> etv-cbxc-lts-s

WORDS

Sometimes, you may prefer your string to be a mix of words. These strings are easier to remember due to their use of vowels.

50001 -> hem-ho
50002 -> nap-pan
100000 -> rich-feet
100001 -> land-sum
100002 -> like-big
1000000 -> wine-safe-farm

Usage

To start using friendly IDs in your Laravel models, simply use the FriendlyId trait in your model class.

Example

Add Trait to a Model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use HadiAghandeh\FriendlyId\Traits\FriendlyId;

class Post extends Model
{
    use FriendlyId;
}

Encode and Decode Friendly IDs

You can now use the encodeFriendlyId method to generate a friendly string representation of the model's ID:

$post = Post::find(1);
$friendlyId = $post->encodeFriendlyId();

echo $friendlyId; // e.g., "abc-def-ghi"

To decode a friendly ID back to the original integer ID, use the decodeFriendlyId method:

$decodedId = Post::decodeFriendlyId('abc-def-ghi');
echo $decodedId; // e.g., 1

Query by Friendly ID

You can use the whereFriendlyId scope to query a model by its friendly ID:

$post = Post::whereFriendlyId('abc-def-ghi')->first();

Configuration Customization

To customize the encoding behavior, you can update your .env file with the following environment variables:

FRIENDLY_ID_ALPHABET=yourcustomalphabet
FRIENDLY_ID_ENCODER=yourencoder
  • FRIENDLY_ID_ALPHABET: Defines the custom alphabet used to generate friendly IDs.
  • FRIENDLY_ID_ENCODER: Defines the encoding mechanism to use. Currently, the default is "SQIDS".

Exception Handling

The decodeFriendlyId method will return null if the provided friendly ID is invalid or cannot be decoded.

$invalidId = Post::decodeFriendlyId('invalid-id'); // returns null

Testing

You can run tests for this package using PHPUnit:

vendor/bin/phpunit

License

This package is open-sourced software licensed under the MIT license.

Support

If this package helps you, please consider giving it a ⭐ on GitHub! Your support means a lot and helps to maintain this project.

hadi-aghandeh/laravel-friendly-id 适用场景与选型建议

hadi-aghandeh/laravel-friendly-id 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 626 次下载、GitHub Stars 达 1, 最近一次更新时间为 2024 年 10 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 hadi-aghandeh/laravel-friendly-id 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-10-06