You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

53 regels
1.6 KiB

  1. <?php
  2. namespace App\Patrones\Singleton;
  3. /**
  4. * If you need to support several types of Singletons in your app, you can
  5. * define the basic features of the Singleton in a base class, while moving the
  6. * actual business logic (like logging) to subclasses.
  7. */
  8. class Singleton
  9. {
  10. /**
  11. * The actual singleton's instance almost always resides inside a static
  12. * field. In this case, the static field is an array, where each subclass of
  13. * the Singleton stores its own instance.
  14. */
  15. private static $instances = [];
  16. /**
  17. * Singleton's constructor should not be public. However, it can't be
  18. * private either if we want to allow subclassing.
  19. */
  20. protected function __construct() { }
  21. /**
  22. * Cloning and unserialization are not permitted for singletons.
  23. */
  24. protected function __clone() { }
  25. public function __wakeup()
  26. {
  27. throw new \Exception("Cannot unserialize singleton");
  28. }
  29. /**
  30. * The method you use to get the Singleton's instance.
  31. */
  32. public static function getInstance()
  33. {
  34. $subclass = static::class;
  35. if (!isset(self::$instances[$subclass])) {
  36. // Note that here we use the "static" keyword instead of the actual
  37. // class name. In this context, the "static" keyword means "the name
  38. // of the current class". That detail is important because when the
  39. // method is called on the subclass, we want an instance of that
  40. // subclass to be created here.
  41. self::$instances[$subclass] = new static();
  42. }
  43. return self::$instances[$subclass];
  44. }
  45. }