Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion pages/Design-Patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,48 @@ yourself a lot of trouble down the road by using factories.
When designing web applications, it often makes sense conceptually and architecturally to allow access to one and only
one instance of a particular class. The singleton pattern enables us to do this.

**TODO: NEED NEW SINGLETON CODE EXAMPLE**
{% highlight php %}
<?php

final class NotificationLogger {
private static ?self $instance = null;

// The constructor is private to prevent creating instances from outside
private function __construct()
{}

// Prevent cloning the instance
private function __clone(): void {}

// Prevent unserialisation which would lead to create a new instance (legacy PHP mechanism, kept for backward compatibility)
public function __wakeup(): void {
throw new \LogicException("Cannot unserialize singleton");
}

// Prevent unserialisation (modern PHP mechanism)
public function __unserialize(array $data): void {
throw new \LogicException("Cannot unserialize singleton");
}

// Creates new instance if it does not exist, otherwise it returns the existing instance
public static function getInstance(): self {
return self::$instance ??= new self();
}

public function log(string $message): void {
echo "[SINGLETON LOG] {$message}";
}
}

// Usage
$logger1 = NotificationLogger::getInstance();
$logger2 = NotificationLogger::getInstance();

// Prove they are the same instance
var_dump($logger1 === $logger2); // bool(true)
$logger1->log("Application started");

{% endhighlight %}

The code above implements the singleton pattern using a [*static* variable](https://www.php.net/language.variables.scope#language.variables.scope.static) and the static creation method `getInstance()`.
Note the following:
Expand Down