bleuren / laravel-api
一个用于使用仓库和服务模式的Laravel API开发的包
v1.0.4
2024-09-04 02:21 UTC
Requires
- php: ^8.3
- illuminate/database: ^11.0
- illuminate/support: ^11.0
README
一个强大的Laravel包,用于在API开发中实现Repository和Service模式。此包通过分离关注点和促进干净的代码架构,为构建可扩展和易于维护的API提供了一个坚实的基础。
功能
- 基础仓库和服务类
- 用于生成仓库和服务的Artisan命令
- 在服务容器中自动绑定仓库和服务
- JSON响应处理
- 易于与Laravel项目集成
要求
- PHP 8.2+
- Laravel 11.0+
安装
- 将包添加到您的Laravel项目中
composer require bleuren/laravel-api
- 发布包配置(可选)
php artisan vendor:publish --provider="Bleuren\LaravelApi\Providers\LaravelApiServiceProvider" --tag="config"
使用方法
创建仓库
要创建一个新的仓库,使用以下Artisan命令
php artisan make:repository User
这将创建一个名为 UserRepository 的新类在 app/Repositories 目录中,并在 app/Contracts 目录中创建相应的 UserRepositoryInterface。
创建服务
要创建一个新的服务,使用以下Artisan命令
php artisan make:service User
这将创建一个名为 UserService 的新类在 app/Services 目录中,并在 app/Contracts 目录中创建相应的 UserServiceInterface。
在控制器中使用仓库和服务
在创建您的仓库和服务后,您可以在控制器中像这样使用它们
use App\Contracts\UserServiceInterface; class UserController extends Controller { protected $userService; public function __construct(UserServiceInterface $userService) { $this->userService = $userService; } public function index() { return $this->userService->all(); } public function show($id) { return $this->userService->find($id); } // ... other methods }
扩展基础类
您可以通过扩展基础仓库和服务类来添加自定义功能
use Bleuren\LaravelApi\BaseRepository; use App\Models\User; class UserRepository extends BaseRepository { public function __construct(User $model) { parent::__construct($model); } // Add custom methods here }
use Bleuren\LaravelApi\BaseService; use App\Contracts\UserRepositoryInterface; class UserService extends BaseService { public function __construct(UserRepositoryInterface $repository) { parent::__construct($repository); } // Add custom methods here }
贡献
欢迎贡献!请随时提交一个Pull Request。
许可证
此包是开源软件,许可协议为 MIT许可证。