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

Alt Multiton UML Diagram

1.4.4. Code

You can also find this code on GitHub

Multiton.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\Multiton;
  4.  
  5. final class Multiton
  6. {
  7. const INSTANCE_1 = '1';
  8. const INSTANCE_2 = '2';
  9.  
  10. /**
  11. * @var Multiton[]
  12. */
  13. private static $instances = [];
  14.  
  15. /**
  16. * this is private to prevent from creating arbitrary instances
  17. */
  18. private function __construct()
  19. {
  20. }
  21.  
  22. public static function getInstance(string $instanceName): Multiton
  23. {
  24. if (!isset(self::$instances[$instanceName])) {
  25. self::$instances[$instanceName] = new self();
  26. }
  27.  
  28. return self::$instances[$instanceName];
  29. }
  30.  
  31. /**
  32. * prevent instance from being cloned
  33. */
  34. private function __clone()
  35. {
  36. }
  37.  
  38. /**
  39. * prevent instance from being unserialized
  40. */
  41. private function __wakeup()
  42. {
  43. }
  44. }

1.4.5. Test