Skip to Content
Course content

246: Common PHP Interview Questions on Design Patterns

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 PaymentStrategy interface with a single method: pay(float $amount): bool.
  • Implement this interface in three classes: PayPalGateway, StripeGateway, and SquareGateway.
  • Create a PaymentFactory class with a static create($gatewayName) method that returns the appropriate gateway instance based on a string input.
  • Write a small execution script that uses the PaymentFactory to instantiate a gateway based on a variable $chosenGateway = 'stripe'; and then calls the pay(100.00) method.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.