Interfaces in PHP (Flexible, Testable Design)
Use interfaces to define contracts, enabling clean architecture and easy mocking in tests.
An interface defines a contract: “any class that implements this must provide these methods.”
This is powerful for: - clean architecture - swapping implementations - unit testing (mocking)
Example: PaymentGateway interface
```php <?php interface PaymentGateway { public function charge(float $amount): bool; }
class StripeGateway implements PaymentGateway { public function charge(float $amount): bool { return true; } }
class CheckoutService { public function __construct(private PaymentGateway $gateway) {}
public function pay(float $amount): bool { return $this->gateway->charge($amount); } }
$checkout = new CheckoutService(new StripeGateway()); $checkout->pay(50); ?> ```
Why this is professional
CheckoutService does not care if you use Stripe, PayPal, or something else. That means your code is easier to maintain.
> Next: Namespaces, avoid class name conflicts in real projects.