kayrunm/polybind

针对 Laravel 的多态路由模型绑定。

0.2 2023-09-14 21:08 UTC

This package is auto-updated.

Last update: 2024-09-14 23:51:51 UTC


README

针对 Laravel 的多态路由模型绑定。

先决条件

此包需要以下内容

  • PHP 8.2
  • Laravel 10 或更高版本

安装

要安装此包,只需运行以下命令

composer require kayrunm/polybind

包的服务提供程序将自动注册,但如果愿意,您可以在您的 config/app.php 文件中添加以下内容

'providers' => [
    // ...
    Kayrunm\Polybind\PolybindServiceProvider::class,
],

最后,您只需在 app/Http/Kernel.php 中的 $middlewareAliases 中将中间件别名化

protected $middlewareAliases = [
    // ...
    'polybind' => Kayrunm\Polybind\Polybind::class
];

如果您没有使用 按路由参数 的打算,可以跳过中间件别名化,因为它只是使添加中间件参数更容易。如果您跳过此步骤,您将必须使用完整的 Polybind 类名来应用中间件。

配置

此包允许您配置默认路由参数和解析逻辑。要开始,您需要发布配置文件

php artisan vendor:publish --provider="Kayrunm\Polybind\PolybindServiceProvider"

现在您可以使用您选择的默认值编辑 config/polybind.php 文件。

用法

Polybind 通过您添加到多态路由的中间件工作。开始使用它的最简单方法是将其添加到路由定义中,如下所示

// routes/web.php

Route::get('/{model_type}/{model_id}', [MyController::class, 'show'])->middleware('polybind');

当您访问此路由时,Polybind 将执行其魔法,通过自动解析模型并允许您通过 $model 参数在控制器方法中访问模型。

// MyController.php

public function show($model)
{
    return response()->json($model);
}

注意: Polybind 要求您的模型在 Relation::morphMap() 中注册。

类型验证

Polybind 允许您通过联合/交集类型或甚至通过接口提示接受的路由模型的类型。如果 Polybind 解析的模型与您提示的类型不匹配,它将抛出 Kayrum\Polybind\Exceptions\InvalidModelType 异常。如果您在控制器方法中没有使用任何类型提示,Polybind 将允许解析任何模型。

以下是一个使用接口进行类型提示的示例

// MyController.php

public function show(HasAuthor $model)
{
    return response()->json($model);
}

以下是一个使用联合类型进行类型提示的示例

// MyController.php

public function show(Post|Comment $model)
{
    return response()->json($model);
}

按路由配置

Polybind 还允许您按路由配置模型类型和模型标识符的路由参数,以及您在控制器方法中使用的参数名称。以下是如何做到这一点的示例

// routes/web.php

Route::get('/{author_type}/{author_uuid}', function ($author) {
    return response()->json($author);
})->middleware('polybind:author_type,author_uuid,author');

添加到整个应用程序

如果您在整个应用程序中使用多态路由模型绑定,您可能发现将 Polybind 的功能应用于所有路由更简单。Polybind 只在找到匹配的类型 标识符参数的路由上运行。

为此,只需将 Polybind 中间件添加到您希望它运行的中间件组中,例如在 app/Http/Kernel.php 中的 webapi 组中

protected $middlewareGroups = [
    'web' => [
        // ...
        \Kayrunm\Polybind\Polybind::class,    
    ],
    
    'api' => [
        // ...
        \Kayrunm\Polybind\Polybind::class,    
    ],
];

注意: 确保在 SubstituteBindings 中间件之后应用 Polybind 中间件。