visiarch / laravel-repository
一个简单的 Laravel 包,用于通过 artisan 命令创建仓库
1.0.0
2024-06-29 05:40 UTC
README
laravel-repository
一个简单的包,用于在 Laravel 中使用 artisan 命令创建仓库。
此包扩展了 make:
命令,帮助您在 Laravel 9+ 中轻松创建仓库类。
什么是仓库?
仓库是一种用于管理数据访问逻辑的设计模式。它提供了应用程序与数据访问层(如数据库)之间的抽象。
安装
composer require visiarch/laravel-repository
安装完成后,您可以在终端中使用其中的任何命令。
用法
仓库用于将数据访问逻辑与业务逻辑分离,使开发者可以更改数据的存储和检索方式,而不会影响业务逻辑。
使用接口
php artisan make:repository {name} --i
不使用接口
php artisan make:repository {name}
示例
使用接口创建仓库类
php artisan make:repository PostRepository --i
app/Repositories/Interfaces/PostRepositoryInterface.php
<?php namespace App\Repositories\Interfaces; /** * Interface PostRepositoryInterface * * This interface defines the methods for the PostRepository class. */ interface PostRepositoryInterface { // }
app/Repositories/PostRepository.php
<?php namespace App\Repositories; use App\Repositories\Interfaces\PostRepositoryInterface; /** * Class PostRepository * * @package App\Repositories */ class PostRepository implements PostRepositoryInterface { // }
app\Providers/AppServiceProvider
public function register(): void { // $this->app->bind( \App\Repositories\Interfaces\PostRepositoryInterface::class, \App\Repositories\PostRepository::class ); }
不使用接口创建仓库类
php artisan make:repository PostRepository
app/Repositories/PostRepository.php
<?php namespace App\Repositories; /** * Class PostRepository * * @package App\Repositories */ class PostRepository { // }
实现
使用接口
<?php namespace App\Repositories\Interfaces; use App\Models\Post; class PostRepository implements PostRepositoryInterface { public function store(array $data): Post; }
<?php namespace App\Repositories; use App\Models\Post; class PostRepository implements PostRepositoryInterface { protected $post; public function __construct(Post $post){ $this->post = $post; } public function store(array $data): Post { return $this->post->create($data); } }
不使用接口
<?php namespace App\Repositories; use App\Models\Post; class PostRepository { protected $post; public function __construct(Post $post){ $this->post = $post; } public function store(array $data): Post { return $this->post->create($data); } }
如何在控制器中实现它?
<?php namespace App\Repositories; use App\Models\Post; use App\Repositories\Interfaces\PostServiceInterface; use App\Http\Requests\PostRequest; class PostController extends Controller { protected $postService; public function __construct(PostServiceInterface $postService) { $this->postService = $postService; } public function store(PostRequest $request): RedirectResponse { $data = $request->validated(); $this->postService->store($data); return redirect()->route('posts.index')->with('success', __('post created')); } }
Just change PostRepositoryInterface to PostRepository if you are implementing without interface
贡献
请随意分支此包,并通过提交拉取请求来增强功能。
我该如何感谢你?
为何不点赞 GitHub 仓库?我很乐意得到关注!为何不在任何社交媒体上分享此仓库链接?传播信息!
谢谢!visiarch
许可证
MIT 许可证(MIT)。请参阅 许可证文件 获取更多信息。