Bind interfaces to implementations in the IoC container and inject dependencies via constructors.
Service Container and DI
// Binding in ServiceProvider
class AppServiceProvider extends ServiceProvider {
public function register(): void {
// Bind interface to implementation
$this->app->bind(PaymentGateway::class, StripeGateway::class);
// Singleton — same instance each time
$this->app->singleton(Analytics::class, fn($app) =>
new Analytics($app->make(HttpClient::class))
);
// Instance
$this->app->instance("config.key", "value");
}
}
// Auto-injection in controllers
class CheckoutController extends Controller {
public function __construct(
private PaymentGateway $gateway, // auto-resolved!
private OrderService $orders
) {}
}
// Resolve manually
$gateway = app(PaymentGateway::class);
$gateway = resolve(PaymentGateway::class);