Laravel 服务容器与依赖注入深度解析
服务容器是 Laravel 的核心,负责类的解析与依赖管理。
1. 绑定与解析
// 在 AppServiceProvider 中
use App\Services\PaymentService;
use App\Contracts\PaymentInterface;
$this->app->bind(PaymentInterface::class, PaymentService::class);
// 单例
$this->app->singleton(SomeService::class, function ($app) {
return new SomeService($app->make(Config::class));
});2. 依赖注入(构造函数注入)
class OrderController {
public function __construct(private PaymentInterface $payment) {}
public function create() {
$this->payment->charge(100);
}
}3. 门面(Facade)
提供静态风格接口。
use Illuminate\Support\Facades\Cache;
Cache::put('key', 'value', 60);4. 服务提供者
所有服务在 config/app.php 的 providers 数组中注册。
5. 上下文绑定
针对不同需求绑定不同实现。
深入理解容器是 Laravel 高级开发的关键。
