Skip to content
AgileLogics
5 min read

Advanced OOP Patterns

Prerequisites: Level 2 — Intermediate

A few patterns that show up constantly in real PHP codebases:

// Singleton
class AppConfig
{
    private static ?self $instance = null;
    private function __construct() {}

    public static function getInstance(): self
    {
        return self::$instance ??= new self();
    }
}

// Factory
function createShape(string $kind): Shape
{
    return match ($kind) {
        'circle' => new Circle(1.0),
        'square' => new Square(1.0),
        default => throw new InvalidArgumentException("Unknown shape: $kind"),
    };
}

Strategy is what passing a closure or an interface implementation into a method already does (seen throughout Level 2) — swap behavior without an if/else chain at the call site.

Common mistakes

  • Reaching for Singleton by default for anything "global" — it makes testing harder (shared state between tests) and often hides a dependency that should be passed in explicitly instead (see Dependency Injection, next).