Drupal.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * @file
  4. * Contains Drupal 7 foreward compatibility layer for Drupal 8.
  5. */
  6. /**
  7. * Static Service Container wrapper.
  8. *
  9. * Generally, code in Drupal should accept its dependencies via either
  10. * constructor injection or setter method injection. However, there are cases,
  11. * particularly in legacy procedural code, where that is infeasible. This
  12. * class acts as a unified global accessor to arbitrary services within the
  13. * system in order to ease the transition from procedural code to injected OO
  14. * code.
  15. *
  16. */
  17. class Drupal {
  18. /**
  19. * The currently active container object.
  20. *
  21. * @var \Drupal\service_container\DependencyInjection\ContainerInterface
  22. */
  23. protected static $container;
  24. /**
  25. * Returns the currently active global container.
  26. *
  27. * @deprecated This method is only useful for the testing environment. It
  28. * should not be used otherwise.
  29. *
  30. * @return \Drupal\service_container\DependencyInjection\ContainerInterface
  31. */
  32. public static function getContainer() {
  33. return static::$container;
  34. }
  35. /**
  36. * Retrieves a service from the container.
  37. *
  38. * Use this method if the desired service is not one of those with a dedicated
  39. * accessor method below. If it is listed below, those methods are preferred
  40. * as they can return useful type hints.
  41. *
  42. * @param string $id
  43. * The ID of the service to retrieve.
  44. * @return mixed
  45. * The specified service.
  46. */
  47. public static function service($id) {
  48. return static::$container->get($id);
  49. }
  50. /**
  51. * Indicates if a service is defined in the container.
  52. *
  53. * @param string $id
  54. * The ID of the service to check.
  55. *
  56. * @return bool
  57. * TRUE if the specified service exists, FALSE otherwise.
  58. */
  59. public static function hasService($id) {
  60. // @todo Add ->has method to the container to be compatible.
  61. return static::$container && static::$container->hasDefinition($id);
  62. }
  63. }