PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
246: Common PHP Interview Questions on Design Patterns
If you've spent any time prepping for senior PHP roles, you know that "Design Patterns" is a favorite topic for interviewers. But here is the secret: most people just memorize the definitions from a wiki and fail the moment the interviewer asks, "Why would you actually use this over a simple function?"
Instead of reciting definitions, let's actually build something. We're going to build a notification system that sends alerts via Email, SMS, or Slack. I'll start the "wrong" way—the way we usually do when we're rushing a feature—and we'll let the pain lead us to the patterns.
Fighting with the Config Object
First, we need a way to handle API keys for our services. I'll start by creating a Config class. I'll instantiate it in my main script and pass it into every single class that needs it.
$config = new Config(['email_key' => '123', 'sms_key' => '456']);
$emailService = new EmailService($config);
$smsService = new SmsService($config);
$logger = new Logger($config);
Wait. This is already annoying. Every time I add a new service, I'm passing this $config object around like a hot potato. It's boilerplate noise. I wonder... what if I just make the Config class responsible for its own single instance? If I make the constructor private, I can prevent people from creating five different config objects across the app.
class Config {
private static $instance = null;
private $settings = [];
private function __construct() {
// Load from file or env
$this->settings = ['email_key' => '123', 'sms_key' => '456'];
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function get($key) {
return $this->settings[$key] ?? null;
}
}
Now I can just call Config::getInstance()->get('email_key') anywhere. This is the Singleton pattern. Interviewers love to ask about this. The "gotcha" they're looking for? Singletons make unit testing hard because they introduce global state. I'll keep that in my back pocket for the interview.
The Switch Statement from Hell
Now, let's handle the actual notifications. I'll write a bit of logic to decide which service to use based on a user's preference.
if ($user->pref === 'email') {
$notifier = new EmailService();
} elseif ($user->pref === 'sms') {
$notifier = new SmsService();
} elseif ($user->pref === 'slack') {
$notifier = new SlackService();
} else {
throw new Exception("Unknown channel");
}
$notifier->send($message);
This works, but it's fragile. If I add a "WhatsApp" channel tomorrow, I have to hunt down every single place in my codebase where I've written this if/else block and update it. That's a recipe for a production bug. I need to encapsulate this "creation logic" in one place.
class NotificationFactory {
public static function create($type) {
return match($type) {
'email' => new EmailService(),
'sms' => new SmsService(),
'slack' => new SlackService(),
default => throw new Exception("Invalid notification type"),
};
}
}
// Now the client code is clean:
$notifier = NotificationFactory::create($user->pref);
$notifier->send($message);
There it is: the Factory pattern. I've moved the "how to create the object" logic away from the "how to use the object" logic. Now, if I add WhatsApp, I only change one line in the Factory.
Trading Logic for Interfaces
I've noticed a problem. My EmailService has a method called sendEmail(), but my SmsService has sendSms(). My client code is now doing this:
$notifier = NotificationFactory::create($user->pref);
if ($notifier instanceof EmailService) {
$notifier->sendEmail($msg);
} elseif ($notifier instanceof SmsService) {
$notifier->sendSms($msg);
}
This completely defeats the purpose of the Factory! I'm right back to using if/else blocks. The problem is that my classes don't share a common contract. I need to define a Strategy. I'll create an interface that forces every notification service to use the exact same method name.
interface NotificationStrategy {
public function send(string $message): void;
}
class EmailService implements NotificationStrategy {
public function send(string $message): void {
echo "Sending Email: $message";
}
}
class SmsService implements NotificationStrategy {
public function send(string $message): void {
echo "Sending SMS: $message";
}
}
Now, the client code doesn't care which class it's holding. It just knows that whatever it is, it has a send() method. This is the Strategy pattern. It allows me to swap the algorithm (the delivery method) at runtime without changing the code that triggers the notification.
When an interviewer asks about these, don't just tell them what a Factory is. Tell them about the "Switch Statement from Hell" and how the Factory solves it. That shows you've actually felt the pain these patterns were designed to cure.
📋 Practical Task
Exercise: Refactoring the Multi-Payment Gateway
You have been handed a legacy checkout script. Currently, it uses a massive switch statement to handle different payment gateways (PayPal, Stripe, and Square), and each gateway class has different method names (e.g., processPayPalPayment() vs chargeStripeCard()).
Your Task:
- Create a
PaymentStrategyinterface with a single method:pay(float $amount): bool. - Implement this interface in three classes:
PayPalGateway,StripeGateway, andSquareGateway. - Create a
PaymentFactoryclass with a staticcreate($gatewayName)method that returns the appropriate gateway instance based on a string input. - Write a small execution script that uses the
PaymentFactoryto instantiate a gateway based on a variable$chosenGateway = 'stripe';and then calls thepay(100.00)method.
There are no comments for now.