Teknik is a suite of services with attractive and functional interfaces. https://www.teknik.io/
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.

BaseFactory.php 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Piwik - free/libre analytics platform
  4. *
  5. * @link http://piwik.org
  6. * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  7. *
  8. */
  9. namespace Piwik;
  10. use Exception;
  11. use Piwik\Common;
  12. /**
  13. * Base class for all factory types.
  14. *
  15. * Factory types are base classes that contain a **factory** method. This method is used to instantiate
  16. * concrete instances by a specified string ID. Fatal errors do not occur if a class does not exist.
  17. * Instead an exception is thrown.
  18. *
  19. * Derived classes should override the **getClassNameFromClassId** and **getInvalidClassIdExceptionMessage**
  20. * static methods.
  21. */
  22. abstract class BaseFactory
  23. {
  24. /**
  25. * Creates a new instance of a class using a string ID.
  26. *
  27. * @param string $classId The ID of the class.
  28. * @return BaseFactory
  29. * @throws Exception if $classId is invalid.
  30. */
  31. public static function factory($classId)
  32. {
  33. $className = static::getClassNameFromClassId($classId);
  34. if (!class_exists($className)) {
  35. Common::sendHeader('Content-Type: text/plain; charset=utf-8');
  36. throw new Exception(static::getInvalidClassIdExceptionMessage($classId));
  37. }
  38. return new $className;
  39. }
  40. /**
  41. * Should return a class name based on the class's associated string ID.
  42. */
  43. protected static function getClassNameFromClassId($id)
  44. {
  45. return $id;
  46. }
  47. /**
  48. * Should return a message to use in an Exception when an invalid class ID is supplied to
  49. * {@link factory()}.
  50. */
  51. protected static function getInvalidClassIdExceptionMessage($id)
  52. {
  53. return "Invalid class ID '$id' for " . get_called_class() . "::factory().";
  54. }
  55. }