Lab 07: Design Patterns

Objective

Implement the most commonly used design patterns in PHP: Singleton for shared resources, Factory/Abstract Factory for object creation, Observer for event systems, Strategy for swappable algorithms, Decorator for behaviour composition, and Command for encapsulating actions.

Background

Design patterns are reusable solutions to recurring problems. In PHP they appear everywhere: Laravel's IoC container (Singleton + Factory), Symfony's EventDispatcher (Observer), payment gateways (Strategy), middleware stacks (Decorator), and command buses (Command). Learning to recognise and implement patterns makes framework internals transparent.

Time

35 minutes

Prerequisites

  • PHP Practitioner Lab 01 (Traits & Interfaces)

Tools

  • Docker: zchencow/innozverse-php:latest


Lab Instructions

Step 1: Singleton & Factory


Step 2: Observer, Strategy, Decorator, Command

📸 Verified Output:


Summary

Pattern
Intent
PHP Use

Singleton

One instance globally

DB connections, config

Factory

Create objects by type

Gateways, drivers

Observer

Notify listeners of events

Order events, webhooks

Strategy

Swap algorithms at runtime

Sorting, pricing, export

Decorator

Add behaviour by wrapping

Logging, caching, auth

Command

Encapsulate an action

Queue jobs, undo/redo

Further Reading

Last updated