gorankrgovic/laravel-shortable

Laravel 包,用于创建类似 YouTube 的简短 ID。

v1.0.1 2019-03-17 09:18 UTC

This package is auto-updated.

Last update: 2024-09-17 21:54:12 UTC


README

轻松创建类似 YouTube 的短随机唯一 ID(例如 watch?v=e3H73n7U),用于 Laravel/Lumen 中的 Eloquent 模型。

安装

通过 Composer 安装此包

composer require gorankrgovic/laravel-shortable

该包将自动注册其服务提供者。

可选地,如果您想更改任何默认设置,请发布配置文件

php artisan vendor:publish --provider="Gorankrgovic\LaravelShortable\ServiceProvider"

更新您的 Eloquent 模型

您的模型应使用 Shortable 特性,该特性包含一个抽象方法 shortable(),您需要对其进行定义。这是设置任何模型特定配置的地方(有关详细信息,请参阅下面的配置)

use Gorankrgovic\LaravelShortable\Shortable;

class Video extends Model
{
    use Shortable;

    /**
     * Return the shortable configuration array for this model.
     *
     * @return array
     */
    public function shortable()
    {
        return [
            'short_url'
        ];
    }
}

如果您想有多个字段,只需向数组中添加更多即可。

当然,您的模型和数据库需要一列来存储短 ID。您需要手动通过自己的迁移添加该列。

就是这样...您的模型现在是“可简短”的!

用法

保存模型很简单

$video = new Video([
    'whateve' => 'My Awesome Video',
]);

$video->save();

检索简短 ID 也同样简单

$video->short_url;

或您给它取的任何名字。

ShortService 类

生成短链接的所有逻辑都由 \Gorankrgovic\LaravelShortable\Services\ShortService 类处理。

通常,您不需要直接访问此类,尽管有一个静态方法可以用来生成短链接而不实际创建或保存相关模型。

use Gorankrgovic\LaravelShortable\Services\ShortService;

$short = ShortService::createShort(Post::class, 'column_name');

这对于测试包很有用。

您还可以将可选的配置值数组作为第四个参数传递。

事件

包将触发两个 Eloquent 模型事件:“shorting”和“shorted”。

您可以通过其他 Eloquent 模型事件的方式挂钩到这两个事件中的任何一个

Post::registerModelEvent('shorting', function($post) {
    if ($post->someCondition()) {
        // the model won't be shorted
        return false;
    }
});

Post::registerModelEvent('shorted', function($post) {
    Log::info('Post shorted: ' . $post->getShort());
});

附加特性

将可选的 ShortableScopeHelpers 特性添加到您的模型中,使您能够处理模型及其 ID。例如

$post = Post::whereShort($shortString)->get();

$post = Post::findByShort($shortString);

$post = Post::findByShortOrFail($shortString);

由于模型可以有多个短 ID,这需要更多的配置。