parables/laravel-model-nanoid 问题修复 & 功能扩展

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

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

parables/laravel-model-nanoid

Composer 安装命令:

composer require parables/laravel-model-nanoid

包简介

This package allows you to easily work with NanoID in your Laravel models.

README 文档

README

Introduction

Huge thanks to Micheal Dyrynda, whose work inspired me to create this package based on laravel-model-nanoid but uses NanoId instead of UUID.

Why NanoID?

npm trends

Nano ID logo by Anton Lovchikov

A tiny, secure, URL-friendly, unique string ID generator for PHP.

This package is PHP implementation of ai's nanoId. Read its documentation for more information.

  • Fast. It is faster than NanoID.
  • Safe. It uses cryptographically strong random APIs. Can be used in clusters.
  • Compact. It uses a larger alphabet than NanoID (A-Za-z0-9_-). So ID size was reduced from 36 to 21 symbols.
  • Customizable. Size, alphabet and Random Bytes Generator may be overridden.

Note: this package explicitly does not disable auto-incrementing on your Eloquent models. In terms of database indexing, it is generally more efficient to use auto-incrementing integers for your internal querying. Indexing your nanoId column will make lookups against that column fast, without impacting queries between related models.

Installation

This package is installed via Composer. To install, run the following command.

composer require parables/laravel-model-nanoid

Code Samples

In order to use this package, you simply need to import and use the trait within your Eloquent models.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Parables\NanoId\GeneratesNanoId;

class Post extends Model
{
    use GeneratesNanoId;
}

It is assumed that you already have a field named nanoId in your database, which is used to store the generated value. If you wish to use a custom column name, for example if you want your primary id column to be a NanoID, you can define a static nanoIdColumn method in your model.

class Post extends Model
{
    public static function nanoIdColumn(): string
    {
        return 'id';
    }
}

Use NanoId as primary key

If you choose to use a NanoID as your primary model key (id), then use GeneratesNanoIdAsPrimaryKey trait on your model.

<?php

namespace App;

use Parables\NanoId\NanoIdAsPrimaryKey;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use NanoIdAsPrimaryKey;
}

And update your migrations

 Schema::create('users', function (Blueprint $table) {
-     $table->id();
+     $table->string('id')->primary();
 });

This trait also provides a query scope which will allow you to easily find your records based on their NanoID, and respects any custom field name you choose.

// Find a specific post with the default (nanoId) column name
$post = Post::whereNanoId($nanoId)->first();

// Find multiple posts with the default (nanoId) column name
$post = Post::whereNanoId([$first, $second])->get();

// Find a specific post with a custom column name
$post = Post::whereNanoId($nanoId, 'custom_column')->first();

// Find multiple posts with a custom column name
$post = Post::whereNanoId([$first, $second], 'custom_column')->get();

Route model binding

Should you wish to leverage implicit route model binding on your nanoId field, you may use the BindsOnNanoId trait, which will use the value returned by nanoIdColumn(). Should you require additional control over the binding, you may override the getRouteKeyName method directly.

public function getRouteKeyName(): string
{
    return 'nanoId';
}

You can generate multiple NanoID columns for a model by returning an array of column names in the nanoIdColumns() method.

If you use the nanoIdColumns() method, then first element in the array must be the value returned by the nanoIdColumn() method which by default is nanoId. If you overwrite the nanoIdColumn() method, put its return value as the first element in the nanoIdColumns() return array.

When querying using the whereNanoId() scope, the default column - specified by nanoIdColumn() will be used.

class Post extends Model
{
    public static function nanoIdColumns(): array
    {
        return ['nanoId', 'custom_column'];
    }
}

The nanoIdColumns must return an array. You can customize the generated NanoId for each column by using an associative array where the key is the column name and the value is an array with an optional int size and string alphabet keys.

  public static function nanoIdColumns(): array
    {
        // Option 1: array of column names: this will use the default size and alphabets
        return ['nanoId', 'custom_column'];

        // Option 2: an array where each element is an array with a required 'key' property.
        // no id will be generated if key is null. 'size' and 'alphabet' properties are optional
        return [
            ['key'=>'nanoId'], // use the NanoId::SIZE_DEFAULT = 21; and NanoId::ALPHABET_DEFAULT
            ['key'=>'column_one', 'size' => 6, 'alphabets'=> NanoId::ALPHABET_NUMBERS],
            ['key'=>'column_two', 'size' => 10, 'alphabets'=> NanoId::ALPHABET_UUID],
        ];

          // Option 3: an array with a string key and an array value with an optional 'size' and 'alphabet' property. If a 'key' is passed in the value, it overwrites the original array 'key'.
        return [
            ['key'=>'nanoId'], // use the NanoId::SIZE_DEFAULT = 21; and NanoId::ALPHABET_DEFAULT
            'column_one' => ['size' => 6, 'alphabets'=> NanoId::ALPHABET_NUMBERS],
            // will use 'another_column' as the column name instead of 'column_two'
            'column_two' => ['key'=>'another_column', 'size' => 10, 'alphabets'=> NanoId::ALPHABET_UUID],
        ];
    }

The following options are available for the alphabet key.

    NanoId::ALPHABET_DEFAULT => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_'
    NanoId::ALPHABET_NUMBERS =>'0123456789'NanoId::ALPHABET_NUMBERS_READABLE => '346789'
    NanoId::ALPHABET_LOWERCASE => 'abcdefghijklmnopqrstuvwxyz'
    NanoId::ALPHABET_LOWERCASE_READABLE => 'abcdefghijkmnpqrtwxyz'
    NanoId::ALPHABET_UPPERCASE => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    NanoId::ALPHABET_UPPERCASE_READABLE => 'ABCDEFGHIJKMNPQRTWXYZ'
    NanoId::ALPHABET_ALPHA_NUMERIC => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
            // Numbers and English alphabet without unreadable letters: 1, l, I, 0, O, o, u, v, 5, S, s, 2, Z
    NanoId::ALPHABET_ALPHA_NUMERIC_READABLE => '346789abcdefghijkmnpqrtwxyzABCDEFGHJKLMNPQRTUVWXY'
            // Same as ALPHABET_ALPHA_NUMERIC_READABLE but with removed vowels and following letters: 3, 4, x, X, V.
    NanoId::ALPHABET_ALPHA_NUMERIC_READABLE_SAFE => '6789bcdfghjkmnpqrtwzBCDFGHJKLMNPQRTW'
    NanoId::ALPHABET_UUID => '0123456789abcdef'

Support

If you are having general issues with this package, feel free to contact me on Twitter.

If you believe you have found an issue, please report it using the GitHub issue tracker, or better yet, fork the repository and submit a pull request.

If you're using this package, I'd love to hear your thoughts. Thanks!

Treeware

You're free to use this package, but if it makes it to your production environment you are required to buy the world a tree.

It’s now common knowledge that one of the best tools to tackle the climate crisis and keep our temperatures from rising above 1.5C is to plant trees. If you support this package and contribute to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

You can buy trees here

Read more about Treeware at treeware.earth

Tools

Credits

parables/laravel-model-nanoid 适用场景与选型建议

parables/laravel-model-nanoid 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5.47k 次下载、GitHub Stars 达 19, 最近一次更新时间为 2022 年 05 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 parables/laravel-model-nanoid 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 5.47k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 20
  • 点击次数: 22
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 19
  • Watchers: 1
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-05-03