Laravel 服务容器和依赖注入流程
·
创建接口——》创建服务者——》使用容器自动绑定(替代服务提供者)——》创建控制器
步骤 1:创建服务接口
bash
php artisan make:contract Services/UserServiceInterface
接口文件位置:app/Contracts/Services/UserServiceInterface.php
步骤 2:创建服务实现
bash
php artisan make:service UserService --interface=UserServiceInterface
实现文件位置:app/Services/UserService.php
步骤 3:使用容器自动绑定(替代服务提供者)
Laravel 服务容器支持基于命名约定的自动绑定,如果你遵循 Interface 和 InterfaceImplementation 的命名模式,可以跳过服务提供者注册步骤。
如果需要显式绑定,可以在 AppServiceProvider 中完成:
php
// app/Providers/AppServiceProvider.php
use App\Contracts\Services\UserServiceInterface;
use App\Services\UserService;
public function register()
{
$this->app->bind(UserServiceInterface::class, UserService::class);
}
无需额外创建服务提供者,Laravel 会自动解析依赖。
步骤 4:创建控制器并注入服务
bash
php artisan make:controller UserController
php
// app/Http/Controllers/UserController.php
use App\Contracts\Services\UserServiceInterface;
class UserController extends Controller
{
private $userService;
public function __construct(UserServiceInterface $userService)
{
$this->userService = $userService;
}
public function index()
{
return $this->userService->getAllUsers();
}
}
步骤 5:定义路由
php
// routes/api.php 或 routes/web.php
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
更多推荐


所有评论(0)