smashed-egg / laravel-model-repository
为Laravel添加模型仓库支持
0.3.0
2023-09-27 09:29 UTC
Requires
- php: ^8.0.2
- illuminate/console: ^9.21|^10.0
- illuminate/contracts: ^9.21|^10.0
- illuminate/support: ^9.21|^10.0
Requires (Dev)
- orchestra/testbench: ^7.6|^8.0
- phpunit/phpunit: ^9.5
README
Laravel模型仓库
本包为喜欢SOLID原则(关注点分离等)并且希望将仓库逻辑放在不同类中的人提供仓库类。
要求
- PHP 8.0.2+
- Laravel 9.0+
安装
要安装此包,请运行
composer require smashed-egg/laravel-model-repository
您可以将包中提供的配置文件发布
php artisan vendor:publish --provider="SmashedEgg\LaravelModelRepository\ServiceProvider"
支持我
你喜欢这个包吗?它是否提高了你的开发效率。考虑赞助以帮助未来的开发。
谢谢!
用法
配置(可选)
如果您已发布了配置文件(位于config/smashed_egg/model_repository.php),您可以使用make命令覆盖基类仓库,以及模型到仓库的映射,这在使用RepositoryManager类时非常有用(后面会详细介绍)。
<?php return [ /** * The base Repository Class to use for all Repositories generated via cli */ 'base_repository' => \SmashedEgg\LaravelModelRepository\Repository\Repository::class, /** * Map of Models to Repository classes * * Useful when using the RepositoryManager class */ 'model_repository_map' => [ //\App\Models\User::class => \App\Repositories\UserRepository::class, ], ];
创建模型仓库
您可以使用以下命令为您的模型创建一个新的仓库,假设您已经有了一个User模型
php artisan smashed-egg:make:repository UserRepository
或使用命令别名
php artisan se:make:repository UserRepository
您甚至可以覆盖基类仓库
php artisan se:make:repository UserRepository --base-repository="App\Repositories\CustomRepository"
默认情况下,您将获得以下方法,这些方法将传递给模型实例
- save(Model $model)
- delete(Model $model, bool $force = false) - 当使用SoftDeletes trait时,您可以控制是否要软删除或硬删除
- restore(Model $model) - 当使用SoftDeletes trait时,您可以撤销软删除
- query - 开始Eloquent查询
- baseQuery - 开始数据库查询
使用RepositoryManager
如果您已配置了模型到仓库的映射