1.4. Multiton
THIS IS CONSIDERED TO BE AN ANTI-PATTERN! FOR BETTER TESTABILITY ANDMAINTAINABILITY USE DEPENDENCY INJECTION!
1.4.1. Purpose
To have only a list of named instances that are used, like a singletonbut with n instances.
1.4.2. Examples
- 2 DB Connectors, e.g. one for MySQL, the other for SQLite
- multiple Loggers (one for debug messages, one for errors)
1.4.3. UML Diagram
1.4.4. Code
You can also find this code on GitHub
Multiton.php
- <?php
- namespace DesignPatterns\Creational\Multiton;
- final class Multiton
- {
- const INSTANCE_1 = '1';
- const INSTANCE_2 = '2';
- /**
- * @var Multiton[]
- */
- private static $instances = [];
- /**
- * this is private to prevent from creating arbitrary instances
- */
- private function __construct()
- {
- }
- public static function getInstance(string $instanceName): Multiton
- {
- if (!isset(self::$instances[$instanceName])) {
- self::$instances[$instanceName] = new self();
- }
- return self::$instances[$instanceName];
- }
- /**
- * prevent instance from being cloned
- */
- private function __clone()
- {
- }
- /**
- * prevent instance from being unserialized
- */
- private function __wakeup()
- {
- }
- }