约 2 分钟阅读
服务容器 (Service Container)
Laravel 的服务容器是一个用于管理类依赖和执行依赖注入的强大工具。几乎所有核心框架服务(数据库、邮件、队列)均由容器进行解析与装配。
基础绑定与解析
简单绑定 (Bind)
use App\Services\PaymentGateway;
use App\Services\StripePaymentGateway;
// 绑定接口到具体实现
$this->app->bind(PaymentGateway::class, function ($app) {
return new StripePaymentGateway(config('services.stripe.secret'));
});
单例绑定 (Singleton)
单例模式确保在同一个应用生命周期中,该类只会被实例化一次:
$this->app->singleton(PaymentGateway::class, function ($app) {
return new StripePaymentGateway(config('services.stripe.secret'));
});
零配置自动注入 (Zero Configuration)
对于大多数没有特定配置依赖的普通类,服务容器可以通过 PHP 的反射机制自动解析类型提示,无需手动注册:
namespace App\Http\Controllers;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
class UserController extends Controller
{
// 容器自动注入 UserRepository 与 Request 实例
public function index(Request $request, UserRepository $users)
{
return response()->json($users->allActive());
}
}