bullet / doctrine-utils
这是我开发的 doctrine-utils 包
v1.0
2024-07-24 14:29 UTC
Requires
- php: ^8.1|^8.2
- laravel-doctrine/orm: ^1.0|2.1
Requires (Dev)
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.1.1||^7.10.0
- orchestra/testbench: ^9.0.0||^8.22.0
- pestphp/pest: ^2.34
- pestphp/pest-plugin-arch: ^2.7
- pestphp/pest-plugin-laravel: ^2.3
- spatie/laravel-ray: ^1.35
This package is auto-updated.
Last update: 2024-09-24 14:49:33 UTC
README
Doctrine Utils 是一个包,旨在通过集成 Doctrine ORM 的高级功能来增强 Laravel 应用程序的功能,以实现更好的路由模型绑定。
特性
路由模型绑定
此功能允许您用 Doctrine 强大的 ORM 功能替换 Laravel 的默认模型绑定。通过使用 Doctrine 进行模型绑定,您可以充分利用 Doctrine 的功能来检索实体。
安装
要安装路由模型绑定功能,请按照以下步骤操作
-
替换 Laravel 中间件:用 Doctrine Utils 提供的中间件替换默认的 Laravel "替换绑定" 中间件。更新您的
Kernel.php
中间件配置,使用以下中间件// In app/Http/Kernel.php protected $middlewareGroups = [ 'web' => [ \Bullet\DoctrineUtils\Http\Middleware\SubstituteBindings::class, 'domain.redirect', ], ];
-
实现 UrlRoutable 接口:将
UrlRoutable
接口添加到您的基实体中,并实现所需的方法。此接口对于中间件使用 Doctrine 实体仓库解析路由绑定是必要的。以下是如何实现它的示例namespace App\Entities; use Bullet\DoctrineUtils\Interfaces\UrlRoutable; class BaseEntity implements UrlRoutable { // Implement the required methods /** * Resolve the route binding. * * @param mixed $value * @param string|null $field * @return mixed */ public static function resolveRouteBinding($value, $field = null) { $field = $field ?? self::getRouteKeyName(); return self::repository()->findOneBy([$field => $value]); } /** * Get the route key name. * * @return string */ public static function getRouteKeyName(): string { return 'id'; } /** * Get the repository for the entity. * * @return \Doctrine\ORM\EntityRepository */ public static function repository() { return app('em')->getRepository(get_called_class()); } }
使用方法
安装后,Doctrine Utils 包将自动使用 Doctrine 实体仓库处理路由模型绑定。这允许您像往常一样定义 Laravel 中的路由和控制器,同时受益于 Doctrine 提供的增强 ORM 功能。
示例
以下是如何工作的示例
-
定义路由
use Illuminate\Support\Facades\Route; Route::get('{plant}', [PlantController::class, 'show']); Route::get('{plant:slug}', [PlantController::class, 'showBySlug']);
-
控制器方法
namespace App\Http\Controllers; use App\Entities\Plant; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class PlantController extends Controller { /** * Show the plant details. * * @param Plant $plant * @param Request $request * @return Response */ public function show(Plant $plant, Request $request): Response { // Handle the request with the injected Plant entity } /** * Show the plant details by slug. * * @param Plant $plant * @param Request $request * @return Response */ public function showBySlug(Plant $plant, Request $request): Response { // Handle the request with the injected Plant entity } }
要求
- Laravel 8.x 或更高版本
- Doctrine ORM
许可
Doctrine Utils 是开源软件,许可协议为 MIT。请随意贡献或修改此包以满足您的需求。
贡献
如果您想为 Doctrine Utils 贡献,请将其仓库分叉