visiarch / laravel-service
一个简单的 Laravel 扩展包,用于创建服务,使用 artisan 命令
1.0.0
2024-06-28 09:28 UTC
README
laravel-service
一个简单的包,用于使用 Laravel 的 artisan 命令创建服务。
此包扩展了 make:
命令,以帮助您轻松地在 Laravel 9+ 中创建服务类。
什么是服务?
服务是一个负责执行应用程序业务逻辑的组件。这是一个放置可能过于复杂或不适合放在控制器中的逻辑的地方。
安装
composer require visiarch/laravel-service
安装完成后,您可以在终端中使用任何命令。
用法
服务用于将业务逻辑与控制器分离,使控制器更简洁,专注于处理 HTTP 请求并提供适当的响应。
使用接口
php artisan make:service {name} --i
不使用接口
php artisan make:service {name}
示例
使用接口创建服务类
php artisan make:service PostService --i
app/Services/Interfaces/PostServiceInterface.php
<?php namespace App\Services\Interfaces; /** * Interface PostServiceInterface * * This interface defines the methods for the PostService class. */ interface PostServiceInterface { // }
app/Services/PostService.php
<?php namespace App\Services; use App\Services\Interfaces\PostServiceInterface; /** * Class PostService * * @package App\Services */ class PostService implements PostServiceInterface { // }
app\Providers\AppServiceProvider
public function register(): void { // $this->app->bind( \App\Services\Interfaces\PostServiceInterface::class, \App\Services\PostService::class ); }
不使用接口创建服务类
php artisan make:service PostService
app/Services/PostService.php
<?php namespace App\Services; /** * Class PostService * * @package App\Services */ class PostService { // }
实现
使用接口
<?php namespace App\Services\Interfaces; use App\Models\Post; class PostService implements PostServiceInterface { public function store(array $data): Post; }
<?php namespace App\Services; use App\Models\Post; class PostService implements PostServiceInterface { public function store(array $data): Post { return Post::create($data); } }
不使用接口
<?php namespace App\Services; use App\Models\Post; class PostService { public function store(array $data): Post { return Post::create($data); } }
如何在控制器中实现它?
<?php namespace App\Services; use App\Models\Post; use App\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 PostServiceInterface to PostService if you are implementing without interface
贡献
请随意fork此包,并通过提交拉取请求来贡献功能。
我该如何感谢您?
为什么不给 GitHub 仓库加星?我会很高兴得到关注!为什么不分享此存储库的链接到任何社交媒体?传播这个消息!
谢谢!visiarch
许可证
MIT 许可证 (MIT)。请参阅 许可证文件 了解更多信息。