Contains \Drupal.

File

core/lib/Drupal.php
View source
  1. <?php
  2. /**
  3. * @file
  4. * Contains \Drupal.
  5. */
  6. use Drupal\Core\DependencyInjection\ContainerNotInitializedException;
  7. use Symfony\Component\DependencyInjection\ContainerInterface;
  8. use Drupal\Core\Url;
  9. /**
  10. * Static Service Container wrapper.
  11. *
  12. * Generally, code in Drupal should accept its dependencies via either
  13. * constructor injection or setter method injection. However, there are cases,
  14. * particularly in legacy procedural code, where that is infeasible. This
  15. * class acts as a unified global accessor to arbitrary services within the
  16. * system in order to ease the transition from procedural code to injected OO
  17. * code.
  18. *
  19. * The container is built by the kernel and passed in to this class which stores
  20. * it statically. The container always contains the services from
  21. * \Drupal\Core\CoreServiceProvider, the service providers of enabled modules and any other
  22. * service providers defined in $GLOBALS['conf']['container_service_providers'].
  23. *
  24. * This class exists only to support legacy code that cannot be dependency
  25. * injected. If your code needs it, consider refactoring it to be object
  26. * oriented, if possible. When this is not possible, for instance in the case of
  27. * hook implementations, and your code is more than a few non-reusable lines, it
  28. * is recommended to instantiate an object implementing the actual logic.
  29. *
  30. * @code
  31. * // Legacy procedural code.
  32. * function hook_do_stuff() {
  33. * $lock = lock()->acquire('stuff_lock');
  34. * // ...
  35. * }
  36. *
  37. * // Correct procedural code.
  38. * function hook_do_stuff() {
  39. * $lock = \Drupal::lock()->acquire('stuff_lock');
  40. * // ...
  41. * }
  42. *
  43. * // The preferred way: dependency injected code.
  44. * function hook_do_stuff() {
  45. * // Move the actual implementation to a class and instantiate it.
  46. * $instance = new StuffDoingClass(\Drupal::lock());
  47. * $instance->doStuff();
  48. *
  49. * // Or, even better, rely on the service container to avoid hard coding a
  50. * // specific interface implementation, so that the actual logic can be
  51. * // swapped. This might not always make sense, but in general it is a good
  52. * // practice.
  53. * \Drupal::service('stuff.doing')->doStuff();
  54. * }
  55. *
  56. * interface StuffDoingInterface {
  57. * public function doStuff();
  58. * }
  59. *
  60. * class StuffDoingClass implements StuffDoingInterface {
  61. * protected $lockBackend;
  62. *
  63. * public function __construct(LockBackendInterface $lock_backend) {
  64. * $this->lockBackend = $lock_backend;
  65. * }
  66. *
  67. * public function doStuff() {
  68. * $lock = $this->lockBackend->acquire('stuff_lock');
  69. * // ...
  70. * }
  71. * }
  72. * @endcode
  73. *
  74. * @see \Drupal\Core\DrupalKernel
  75. */
  76. class Drupal {
  77. /**
  78. * The current system version.
  79. */
  80. const VERSION = '8.0.4-dev';
  81. /**
  82. * Core API compatibility.
  83. */
  84. const CORE_COMPATIBILITY = '8.x';
  85. /**
  86. * Core minimum schema version.
  87. */
  88. const CORE_MINIMUM_SCHEMA_VERSION = 8000;
  89. /**
  90. * The currently active container object, or NULL if not initialized yet.
  91. *
  92. * @var \Symfony\Component\DependencyInjection\ContainerInterface|null
  93. */
  94. protected static $container;
  95. /**
  96. * Sets a new global container.
  97. *
  98. * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
  99. * A new container instance to replace the current.
  100. */
  101. public static function setContainer(ContainerInterface $container) {
  102. static::$container = $container;
  103. }
  104. /**
  105. * Unsets the global container.
  106. */
  107. public static function unsetContainer() {
  108. static::$container = NULL;
  109. }
  110. /**
  111. * Returns the currently active global container.
  112. *
  113. * @return \Symfony\Component\DependencyInjection\ContainerInterface|null
  114. *
  115. * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException
  116. */
  117. public static function getContainer() {
  118. if (static::$container === NULL) {
  119. throw new ContainerNotInitializedException('\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.');
  120. }
  121. return static::$container;
  122. }
  123. /**
  124. * Returns TRUE if the container has been initialized, FALSE otherwise.
  125. *
  126. * @return bool
  127. */
  128. public static function hasContainer() {
  129. return static::$container !== NULL;
  130. }
  131. /**
  132. * Retrieves a service from the container.
  133. *
  134. * Use this method if the desired service is not one of those with a dedicated
  135. * accessor method below. If it is listed below, those methods are preferred
  136. * as they can return useful type hints.
  137. *
  138. * @param string $id
  139. * The ID of the service to retrieve.
  140. *
  141. * @return mixed
  142. * The specified service.
  143. */
  144. public static function service($id) {
  145. return static::getContainer()->get($id);
  146. }
  147. /**
  148. * Indicates if a service is defined in the container.
  149. *
  150. * @param string $id
  151. * The ID of the service to check.
  152. *
  153. * @return bool
  154. * TRUE if the specified service exists, FALSE otherwise.
  155. */
  156. public static function hasService($id) {
  157. // Check hasContainer() first in order to always return a Boolean.
  158. return static::hasContainer() && static::getContainer()->has($id);
  159. }
  160. /**
  161. * Gets the app root.
  162. *
  163. * @return string
  164. */
  165. public static function root() {
  166. return static::getContainer()->get('app.root');
  167. }
  168. /**
  169. * Indicates if there is a currently active request object.
  170. *
  171. * @return bool
  172. * TRUE if there is a currently active request object, FALSE otherwise.
  173. */
  174. public static function hasRequest() {
  175. // Check hasContainer() first in order to always return a Boolean.
  176. return static::hasContainer() && static::getContainer()->has('request_stack') && static::getContainer()->get('request_stack')->getCurrentRequest() !== NULL;
  177. }
  178. /**
  179. * Retrieves the currently active request object.
  180. *
  181. * Note: The use of this wrapper in particular is especially discouraged. Most
  182. * code should not need to access the request directly. Doing so means it
  183. * will only function when handling an HTTP request, and will require special
  184. * modification or wrapping when run from a command line tool, from certain
  185. * queue processors, or from automated tests.
  186. *
  187. * If code must access the request, it is considerably better to register
  188. * an object with the Service Container and give it a setRequest() method
  189. * that is configured to run when the service is created. That way, the
  190. * correct request object can always be provided by the container and the
  191. * service can still be unit tested.
  192. *
  193. * If this method must be used, never save the request object that is
  194. * returned. Doing so may lead to inconsistencies as the request object is
  195. * volatile and may change at various times, such as during a subrequest.
  196. *
  197. * @return \Symfony\Component\HttpFoundation\Request
  198. * The currently active request object.
  199. */
  200. public static function request() {
  201. return static::getContainer()->get('request_stack')->getCurrentRequest();
  202. }
  203. /**
  204. * Retrives the request stack.
  205. *
  206. * @return \Symfony\Component\HttpFoundation\RequestStack
  207. * The request stack
  208. */
  209. public static function requestStack() {
  210. return static::getContainer()->get('request_stack');
  211. }
  212. /**
  213. * Retrieves the currently active route match object.
  214. *
  215. * @return \Drupal\Core\Routing\RouteMatchInterface
  216. * The currently active route match object.
  217. */
  218. public static function routeMatch() {
  219. return static::getContainer()->get('current_route_match');
  220. }
  221. /**
  222. * Gets the current active user.
  223. *
  224. * @return \Drupal\Core\Session\AccountProxyInterface
  225. */
  226. public static function currentUser() {
  227. return static::getContainer()->get('current_user');
  228. }
  229. /**
  230. * Retrieves the entity manager service.
  231. *
  232. * @return \Drupal\Core\Entity\EntityManagerInterface
  233. * The entity manager service.
  234. *
  235. * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
  236. * Use \Drupal::entityTypeManager() instead in most cases. If the needed
  237. * method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the
  238. * deprecated \Drupal\Core\Entity\EntityManager to find the
  239. * correct interface or service.
  240. */
  241. public static function entityManager() {
  242. return static::getContainer()->get('entity.manager');
  243. }
  244. /**
  245. * Retrieves the entity type manager.
  246. *
  247. * @return \Drupal\Core\Entity\EntityTypeManagerInterface
  248. * The entity type manager.
  249. */
  250. public static function entityTypeManager() {
  251. return static::getContainer()->get('entity_type.manager');
  252. }
  253. /**
  254. * Returns the current primary database.
  255. *
  256. * @return \Drupal\Core\Database\Connection
  257. * The current active database's master connection.
  258. */
  259. public static function database() {
  260. return static::getContainer()->get('database');
  261. }
  262. /**
  263. * Returns the requested cache bin.
  264. *
  265. * @param string $bin
  266. * (optional) The cache bin for which the cache object should be returned,
  267. * defaults to 'default'.
  268. *
  269. * @return \Drupal\Core\Cache\CacheBackendInterface
  270. * The cache object associated with the specified bin.
  271. *
  272. * @ingroup cache
  273. */
  274. public static function cache($bin = 'default') {
  275. return static::getContainer()->get('cache.' . $bin);
  276. }
  277. /**
  278. * Returns an expirable key value store collection.
  279. *
  280. * @param string $collection
  281. * The name of the collection holding key and value pairs.
  282. *
  283. * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
  284. * An expirable key value store collection.
  285. */
  286. public static function keyValueExpirable($collection) {
  287. return static::getContainer()->get('keyvalue.expirable')->get($collection);
  288. }
  289. /**
  290. * Returns the locking layer instance.
  291. *
  292. * @return \Drupal\Core\Lock\LockBackendInterface
  293. *
  294. * @ingroup lock
  295. */
  296. public static function lock() {
  297. return static::getContainer()->get('lock');
  298. }
  299. /**
  300. * Retrieves a configuration object.
  301. *
  302. * This is the main entry point to the configuration API. Calling
  303. * @code \Drupal::config('book.admin') @endcode will return a configuration
  304. * object in which the book module can store its administrative settings.
  305. *
  306. * @param string $name
  307. * The name of the configuration object to retrieve. The name corresponds to
  308. * a configuration file. For @code \Drupal::config('book.admin') @endcode, the config
  309. * object returned will contain the contents of book.admin configuration file.
  310. *
  311. * @return \Drupal\Core\Config\ImmutableConfig
  312. * An immutable configuration object.
  313. */
  314. public static function config($name) {
  315. return static::getContainer()->get('config.factory')->get($name);
  316. }
  317. /**
  318. * Retrieves the configuration factory.
  319. *
  320. * This is mostly used to change the override settings on the configuration
  321. * factory. For example, changing the language, or turning all overrides on
  322. * or off.
  323. *
  324. * @return \Drupal\Core\Config\ConfigFactoryInterface
  325. * The configuration factory service.
  326. */
  327. public static function configFactory() {
  328. return static::getContainer()->get('config.factory');
  329. }
  330. /**
  331. * Returns a queue for the given queue name.
  332. *
  333. * The following values can be set in your settings.php file's $settings
  334. * array to define which services are used for queues:
  335. * - queue_reliable_service_$name: The container service to use for the
  336. * reliable queue $name.
  337. * - queue_service_$name: The container service to use for the
  338. * queue $name.
  339. * - queue_default: The container service to use by default for queues
  340. * without overrides. This defaults to 'queue.database'.
  341. *
  342. * @param string $name
  343. * The name of the queue to work with.
  344. * @param bool $reliable
  345. * (optional) TRUE if the ordering of items and guaranteeing every item
  346. * executes at least once is important, FALSE if scalability is the main
  347. * concern. Defaults to FALSE.
  348. *
  349. * @return \Drupal\Core\Queue\QueueInterface
  350. * The queue object for a given name.
  351. */
  352. public static function queue($name, $reliable = FALSE) {
  353. return static::getContainer()->get('queue')->get($name, $reliable);
  354. }
  355. /**
  356. * Returns a key/value storage collection.
  357. *
  358. * @param string $collection
  359. * Name of the key/value collection to return.
  360. *
  361. * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
  362. */
  363. public static function keyValue($collection) {
  364. return static::getContainer()->get('keyvalue')->get($collection);
  365. }
  366. /**
  367. * Returns the state storage service.
  368. *
  369. * Use this to store machine-generated data, local to a specific environment
  370. * that does not need deploying and does not need human editing; for example,
  371. * the last time cron was run. Data which needs to be edited by humans and
  372. * needs to be the same across development, production, etc. environments
  373. * (for example, the system maintenance message) should use \Drupal::config() instead.
  374. *
  375. * @return \Drupal\Core\State\StateInterface
  376. */
  377. public static function state() {
  378. return static::getContainer()->get('state');
  379. }
  380. /**
  381. * Returns the default http client.
  382. *
  383. * @return \GuzzleHttp\Client
  384. * A guzzle http client instance.
  385. */
  386. public static function httpClient() {
  387. return static::getContainer()->get('http_client');
  388. }
  389. /**
  390. * Returns the entity query object for this entity type.
  391. *
  392. * @param string $entity_type
  393. * The entity type (for example, node) for which the query object should be
  394. * returned.
  395. * @param string $conjunction
  396. * (optional) Either 'AND' if all conditions in the query need to apply, or
  397. * 'OR' if any of them is sufficient. Defaults to 'AND'.
  398. *
  399. * @return \Drupal\Core\Entity\Query\QueryInterface
  400. * The query object that can query the given entity type.
  401. */
  402. public static function entityQuery($entity_type, $conjunction = 'AND') {
  403. return static::getContainer()->get('entity.query')->get($entity_type, $conjunction);
  404. }
  405. /**
  406. * Returns the entity query aggregate object for this entity type.
  407. *
  408. * @param string $entity_type
  409. * The entity type (for example, node) for which the query object should be
  410. * returned.
  411. * @param string $conjunction
  412. * (optional) Either 'AND' if all conditions in the query need to apply, or
  413. * 'OR' if any of them is sufficient. Defaults to 'AND'.
  414. *
  415. * @return \Drupal\Core\Entity\Query\QueryAggregateInterface
  416. * The query object that can query the given entity type.
  417. */
  418. public static function entityQueryAggregate($entity_type, $conjunction = 'AND') {
  419. return static::getContainer()->get('entity.query')->getAggregate($entity_type, $conjunction);
  420. }
  421. /**
  422. * Returns the flood instance.
  423. *
  424. * @return \Drupal\Core\Flood\FloodInterface
  425. */
  426. public static function flood() {
  427. return static::getContainer()->get('flood');
  428. }
  429. /**
  430. * Returns the module handler.
  431. *
  432. * @return \Drupal\Core\Extension\ModuleHandlerInterface
  433. */
  434. public static function moduleHandler() {
  435. return static::getContainer()->get('module_handler');
  436. }
  437. /**
  438. * Returns the typed data manager service.
  439. *
  440. * Use the typed data manager service for creating typed data objects.
  441. *
  442. * @return \Drupal\Core\TypedData\TypedDataManagerInterface
  443. * The typed data manager.
  444. *
  445. * @see \Drupal\Core\TypedData\TypedDataManager::create()
  446. */
  447. public static function typedDataManager() {
  448. return static::getContainer()->get('typed_data_manager');
  449. }
  450. /**
  451. * Returns the token service.
  452. *
  453. * @return \Drupal\Core\Utility\Token
  454. * The token service.
  455. */
  456. public static function token() {
  457. return static::getContainer()->get('token');
  458. }
  459. /**
  460. * Returns the url generator service.
  461. *
  462. * @return \Drupal\Core\Routing\UrlGeneratorInterface
  463. * The url generator service.
  464. */
  465. public static function urlGenerator() {
  466. return static::getContainer()->get('url_generator');
  467. }
  468. /**
  469. * Generates a URL string for a specific route based on the given parameters.
  470. *
  471. * This method is a convenience wrapper for generating URL strings for URLs
  472. * that have Drupal routes (that is, most pages generated by Drupal) using
  473. * the \Drupal\Core\Url object. See \Drupal\Core\Url::fromRoute() for
  474. * detailed documentation. For non-routed local URIs relative to
  475. * the base path (like robots.txt) use Url::fromUri()->toString() with the
  476. * base: scheme.
  477. *
  478. * @param string $route_name
  479. * The name of the route.
  480. * @param array $route_parameters
  481. * (optional) An associative array of parameter names and values.
  482. * @param array $options
  483. * (optional) An associative array of additional options.
  484. * @param bool $collect_bubbleable_metadata
  485. * (optional) Defaults to FALSE. When TRUE, both the generated URL and its
  486. * associated bubbleable metadata are returned.
  487. *
  488. * @return string|\Drupal\Core\GeneratedUrl
  489. * A string containing a URL to the given path.
  490. * When $collect_bubbleable_metadata is TRUE, a GeneratedUrl object is
  491. * returned, containing the generated URL plus bubbleable metadata.
  492. *
  493. * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
  494. * @see \Drupal\Core\Url
  495. * @see \Drupal\Core\Url::fromRoute()
  496. * @see \Drupal\Core\Url::fromUri()
  497. *
  498. * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0.
  499. * Instead create a \Drupal\Core\Url object directly, for example using
  500. * Url::fromRoute().
  501. */
  502. public static function url($route_name, $route_parameters = array(), $options = array(), $collect_bubbleable_metadata = FALSE) {
  503. return static::getContainer()->get('url_generator')->generateFromRoute($route_name, $route_parameters, $options, $collect_bubbleable_metadata);
  504. }
  505. /**
  506. * Returns the link generator service.
  507. *
  508. * @return \Drupal\Core\Utility\LinkGeneratorInterface
  509. */
  510. public static function linkGenerator() {
  511. return static::getContainer()->get('link_generator');
  512. }
  513. /**
  514. * Renders a link with a given link text and Url object.
  515. *
  516. * This method is a convenience wrapper for the link generator service's
  517. * generate() method. For detailed documentation, see
  518. * \Drupal\Core\Routing\LinkGeneratorInterface::generate().
  519. *
  520. * @param string $text
  521. * The link text for the anchor tag.
  522. * @param \Drupal\Core\Url $url
  523. * The URL object used for the link.
  524. *
  525. * @return \Drupal\Core\GeneratedLink
  526. * A GeneratedLink object containing a link to the given route and
  527. * parameters and bubbleable metadata.
  528. *
  529. * @see \Drupal\Core\Utility\LinkGeneratorInterface::generate()
  530. * @see \Drupal\Core\Url
  531. *
  532. * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
  533. * Use \Drupal\Core\Link instead.
  534. * Example:
  535. * @code
  536. * $link = Link::fromTextAndUrl($text, $url);
  537. * @endcode
  538. */
  539. public static function l($text, Url $url) {
  540. return static::getContainer()->get('link_generator')->generate($text, $url);
  541. }
  542. /**
  543. * Returns the string translation service.
  544. *
  545. * @return \Drupal\Core\StringTranslation\TranslationManager
  546. * The string translation manager.
  547. */
  548. public static function translation() {
  549. return static::getContainer()->get('string_translation');
  550. }
  551. /**
  552. * Returns the language manager service.
  553. *
  554. * @return \Drupal\Core\Language\LanguageManagerInterface
  555. * The language manager.
  556. */
  557. public static function languageManager() {
  558. return static::getContainer()->get('language_manager');
  559. }
  560. /**
  561. * Returns the CSRF token manager service.
  562. *
  563. * The generated token is based on the session ID of the current user. Normally,
  564. * anonymous users do not have a session, so the generated token will be
  565. * different on every page request. To generate a token for users without a
  566. * session, manually start a session prior to calling this function.
  567. *
  568. * @return \Drupal\Core\Access\CsrfTokenGenerator
  569. * The CSRF token manager.
  570. *
  571. * @see \Drupal\Core\Session\SessionManager::start()
  572. */
  573. public static function csrfToken() {
  574. return static::getContainer()->get('csrf_token');
  575. }
  576. /**
  577. * Returns the transliteration service.
  578. *
  579. * @return \Drupal\Core\Transliteration\PhpTransliteration
  580. * The transliteration manager.
  581. */
  582. public static function transliteration() {
  583. return static::getContainer()->get('transliteration');
  584. }
  585. /**
  586. * Returns the form builder service.
  587. *
  588. * @return \Drupal\Core\Form\FormBuilderInterface
  589. * The form builder.
  590. */
  591. public static function formBuilder() {
  592. return static::getContainer()->get('form_builder');
  593. }
  594. /**
  595. * Gets the theme service.
  596. *
  597. * @return \Drupal\Core\Theme\ThemeManagerInterface
  598. */
  599. public static function theme() {
  600. return static::getContainer()->get('theme.manager');
  601. }
  602. /**
  603. * Gets the syncing state.
  604. *
  605. * @return bool
  606. * Returns TRUE is syncing flag set.
  607. */
  608. public static function isConfigSyncing() {
  609. return static::getContainer()->get('config.installer')->isSyncing();
  610. }
  611. /**
  612. * Returns a channel logger object.
  613. *
  614. * @param string $channel
  615. * The name of the channel. Can be any string, but the general practice is
  616. * to use the name of the subsystem calling this.
  617. *
  618. * @return \Psr\Log\LoggerInterface
  619. * The logger for this channel.
  620. */
  621. public static function logger($channel) {
  622. return static::getContainer()->get('logger.factory')->get($channel);
  623. }
  624. /**
  625. * Returns the menu tree.
  626. *
  627. * @return \Drupal\Core\Menu\MenuLinkTreeInterface
  628. * The menu tree.
  629. */
  630. public static function menuTree() {
  631. return static::getContainer()->get('menu.link_tree');
  632. }
  633. /**
  634. * Returns the path validator.
  635. *
  636. * @return \Drupal\Core\Path\PathValidatorInterface
  637. */
  638. public static function pathValidator() {
  639. return static::getContainer()->get('path.validator');
  640. }
  641. /**
  642. * Returns the access manager service.
  643. *
  644. * @return \Drupal\Core\Access\AccessManagerInterface
  645. * The access manager service.
  646. */
  647. public static function accessManager() {
  648. return static::getContainer()->get('access_manager');
  649. }
  650. /**
  651. * Returns the redirect destination helper.
  652. *
  653. * @return \Drupal\Core\Routing\RedirectDestinationInterface
  654. * The redirect destination helper.
  655. */
  656. public static function destination() {
  657. return static::getContainer()->get('redirect.destination');
  658. }
  659. /**
  660. * Returns the entity definition update manager.
  661. *
  662. * @return \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface
  663. * The entity definition update manager.
  664. */
  665. public static function entityDefinitionUpdateManager() {
  666. return static::getContainer()->get('entity.definition_update_manager');
  667. }
  668. }

Classes

Namesort descending Description
Drupal Static Service Container wrapper.