Back to Tutorials
OOPAdvanced

Advanced Object Oriented Patterns

Deep dive into SOLID principles, dependency injection, and common design patterns in PHP.

Sarah Chen
January 6, 2026
45 min read

Advanced Object Oriented Patterns in PHP

Master the art of writing clean, maintainable, and scalable PHP code using advanced OOP patterns and SOLID principles.

SOLID Principles

Single Responsibility Principle (SRP)

A class should have only one reason to change:

php
1// Bad - Multiple responsibilities
2class User {
3    public function save() { /* database logic */ }
4    public function sendEmail() { /* email logic */ }
5    public function generateReport() { /* reporting logic */ }
6}
7
8// Good - Single responsibility
9class User {
10    public function __construct(
11        public string $name,
12        public string $email
13    ) {}
14}
15
16class UserRepository {
17    public function save(User $user): void {
18        // Database logic only
19    }
20}

Dependency Injection Pattern

Inject dependencies rather than creating them:

php
1class OrderProcessor {
2    public function __construct(
3        private readonly PaymentGateway $gateway,
4        private readonly NotificationService $notifier,
5        private readonly Logger $logger
6    ) {}
7    
8    public function process(Order $order): void {
9        try {
10            $this->gateway->charge($order->total);
11            $this->notifier->sendConfirmation($order);
12            $this->logger->info('Order processed');
13        } catch (PaymentException $e) {
14            $this->logger->error('Payment failed');
15            throw $e;
16        }
17    }
18}

Design Patterns

Repository Pattern

php
1interface UserRepositoryInterface {
2    public function find(int $id): ?User;
3    public function findByEmail(string $email): ?User;
4    public function save(User $user): void;
5}
6
7class DatabaseUserRepository implements UserRepositoryInterface {
8    public function __construct(
9        private readonly PDO $pdo
10    ) {}
11    
12    public function find(int $id): ?User {
13        $stmt = $this->pdo->prepare('SELECT * FROM users WHERE id = ?');
14        $stmt->execute([$id]);
15        $data = $stmt->fetch();
16        return $data ? User::fromArray($data) : null;
17    }
18}

Factory Pattern

php
1interface PaymentGatewayFactory {
2    public function create(string $type): PaymentGateway;
3}
4
5class PaymentGatewayFactoryImpl implements PaymentGatewayFactory {
6    public function create(string $type): PaymentGateway {
7        return match($type) {
8            'stripe' => new StripeGateway(),
9            'paypal' => new PayPalGateway(),
10            'square' => new SquareGateway(),
11            default => throw new InvalidArgumentException("Unknown gateway")
12        };
13    }
14}

Conclusion

These patterns form the foundation of professional PHP development. Practice implementing them in your projects!