thuanpt / larasitory
一个简单易用的Laravel代码仓库模式
1.0.4
2022-08-23 03:02 UTC
Requires
- php: >=7.1.3
- illuminate/config: >=5.0
- illuminate/console: >=5.0
- illuminate/database: >=5.0
- illuminate/filesystem: >=5.0
- illuminate/http: >=5.0
- illuminate/pagination: >=5.0
- illuminate/support: >=5.0
- illuminate/validation: >=5.0
README
要开始使用 基本仓库,请使用Composer将包添加到项目的依赖中
composer require thuanpt/larasitory
基本用法
接下来,您已经准备好使用仓库。如果您想创建与模型对应的仓库(例如:PostRepository),请运行命令行
php artisan make:repostitory PostRepository -i
运行此命令时,包将在Repository文件夹中自动生成两个文件:PostRepository和PostRepositoryInterface。PostRepository扩展了BaseRepository,因此您可以使用BaseRepository中的方法
<?php namespace App\Repositories; use App\Models\Post; use Larasitory\Repository\BaseRepository; use App\Repositories\Contracts\PostRepositoryInterface; class PostRepository extends BaseRepository implements PostRepositoryInterface { /** * Set model database * * @return mixed|string */ public function model() { return Post::class; } }
在AppServiceProvider中注册
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // } /** * Register any application services. * * @return void */ public function register() { $this->app->bind( \App\Repositories\Contracts\PostRepositoryInterface::class, \App\Repositories\PostRepository::class ); } }
在控制器中使用
在控制器中,您想要通过ID使用仓库查找帖子
<?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\Controller; use App\Repositories\Contracts\PostRepositoryInterface; class PostController extends Controller { /** * @var \App\Repositories\PostRepository */ private $postRepository; public function __construct(PostRepositoryInterface $postRepository ) { $this->postRepository = $postRepository; } public function show($id) { $user = $this->postRepository->getById($id); return response()->json($user); } }