Preparing your workspace
Interfaces define contracts, traits provide reusable behavior, and dependency injection supplies required dependencies from outside a class.
Interfaces allow different classes to follow the same contract without forcing them to share implementation. Traits provide a way to reuse methods across classes, although they should be used carefully. Dependency injection means a class receives the objects it needs instead of creating them internally. This makes code easier to replace, test, and maintain. These concepts become especially important in larger PHP applications and frameworks.
A payment service can depend on a PaymentGateway interface so different gateway implementations can be used without changing the business logic.
<?php
interface PaymentGateway
{
public function charge(float $amount): bool;
}
class PaymentService
{
public function __construct(
private PaymentGateway $gateway
) {
}
public function pay(float $amount): bool
{
return $this->gateway->charge($amount);
}
}PaymentService depends on an interface rather than a specific payment implementation.