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 $lockBackend) {
  64. * $this->lockBackend = $lockBackend;
  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.0-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. * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException
  114. *
  115. * @return \Symfony\Component\DependencyInjection\ContainerInterface|null
  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. * @return mixed
  141. * The specified service.
  142. */
  143. public static function service($id) {
  144. return static::getContainer()->get($id);
  145. }
  146. /**
  147. * Indicates if a service is defined in the container.
  148. *
  149. * @param string $id
  150. * The ID of the service to check.
  151. *
  152. * @return bool
  153. * TRUE if the specified service exists, FALSE otherwise.
  154. */
  155. public static function hasService($id) {
  156. // Check hasContainer() first in order to always return a Boolean.
  157. return static::hasContainer() && static::getContainer()->has($id);
  158. }
  159. /**
  160. * Gets the app root.
  161. *
  162. * @return string
  163. */
  164. public static function root() {
  165. return static::getContainer()->get('app.root');
  166. }
  167. /**
  168. * Indicates if there is a currently active request object.
  169. *
  170. * @return bool
  171. * TRUE if there is a currently active request object, FALSE otherwise.
  172. */
  173. public static function hasRequest() {
  174. // Check hasContainer() first in order to always return a Boolean.
  175. return static::hasContainer() && static::getContainer()->has('request_stack') && static::getContainer()->get('request_stack')->getCurrentRequest() !== NULL;
  176. }
  177. /**
  178. * Retrieves the currently active request object.
  179. *
  180. * Note: The use of this wrapper in particular is especially discouraged. Most
  181. * code should not need to access the request directly. Doing so means it
  182. * will only function when handling an HTTP request, and will require special
  183. * modification or wrapping when run from a command line tool, from certain
  184. * queue processors, or from automated tests.
  185. *
  186. * If code must access the request, it is considerably better to register
  187. * an object with the Service Container and give it a setRequest() method
  188. * that is configured to run when the service is created. That way, the
  189. * correct request object can always be provided by the container and the
  190. * service can still be unit tested.
  191. *
  192. * If this method must be used, never save the request object that is
  193. * returned. Doing so may lead to inconsistencies as the request object is
  194. * volatile and may change at various times, such as during a subrequest.
  195. *
  196. * @return \Symfony\Component\HttpFoundation\Request
  197. * The currently active request object.
  198. */
  199. public static function request() {
  200. return static::getContainer()->get('request_stack')->getCurrentRequest();
  201. }
  202. /**
  203. * Retrives the request stack.
  204. *
  205. * @return \Symfony\Component\HttpFoundation\RequestStack
  206. * The request stack
  207. */
  208. public static function requestStack() {
  209. return static::getContainer()->get('request_stack');
  210. }
  211. /**
  212. * Retrieves the currently active route match object.
  213. *
  214. * @return \Drupal\Core\Routing\RouteMatchInterface
  215. * The currently active route match object.
  216. */
  217. public static function routeMatch() {
  218. return static::getContainer()->get('current_route_match');
  219. }
  220. /**
  221. * Gets the current active user.
  222. *
  223. * @return \Drupal\Core\Session\AccountProxyInterface
  224. */
  225. public static function currentUser() {
  226. return static::getContainer()->get('current_user');
  227. }
  228. /**
  229. * Retrieves the entity manager service.
  230. *
  231. * @return \Drupal\Core\Entity\EntityManagerInterface
  232. * The entity manager service.
  233. */
  234. public static function entityManager() {
  235. return static::getContainer()->get('entity.manager');
  236. }
  237. /**
  238. * Returns the current primary database.
  239. *
  240. * @return \Drupal\Core\Database\Connection
  241. * The current active database's master connection.
  242. */
  243. public static function database() {
  244. return static::getContainer()->get('database');
  245. }
  246. /**
  247. * Returns the requested cache bin.
  248. *
  249. * @param string $bin
  250. * (optional) The cache bin for which the cache object should be returned,
  251. * defaults to 'default'.
  252. *
  253. * @return \Drupal\Core\Cache\CacheBackendInterface
  254. * The cache object associated with the specified bin.
  255. *
  256. * @ingroup cache
  257. */
  258. public static function cache($bin = 'default') {
  259. return static::getContainer()->get('cache.' . $bin);
  260. }
  261. /**
  262. * Returns an expirable key value store collection.
  263. *
  264. * @param string $collection
  265. * The name of the collection holding key and value pairs.
  266. *
  267. * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
  268. * An expirable key value store collection.
  269. */
  270. public static function keyValueExpirable($collection) {
  271. return static::getContainer()->get('keyvalue.expirable')->get($collection);
  272. }
  273. /**
  274. * Returns the locking layer instance.
  275. *
  276. * @return \Drupal\Core\Lock\LockBackendInterface
  277. *
  278. * @ingroup lock
  279. */
  280. public static function lock() {
  281. return static::getContainer()->get('lock');
  282. }
  283. /**
  284. * Retrieves a configuration object.
  285. *
  286. * This is the main entry point to the configuration API. Calling
  287. * @code \Drupal::config('book.admin') @endcode will return a configuration
  288. * object in which the book module can store its administrative settings.
  289. *
  290. * @param string $name
  291. * The name of the configuration object to retrieve. The name corresponds to
  292. * a configuration file. For @code \Drupal::config('book.admin') @endcode, the config
  293. * object returned will contain the contents of book.admin configuration file.
  294. *
  295. * @return \Drupal\Core\Config\ImmutableConfig
  296. * An immutable configuration object.
  297. */
  298. public static function config($name) {
  299. return static::getContainer()->get('config.factory')->get($name);
  300. }
  301. /**
  302. * Retrieves the configuration factory.
  303. *
  304. * This is mostly used to change the override settings on the configuration
  305. * factory. For example, changing the language, or turning all overrides on
  306. * or off.
  307. *
  308. * @return \Drupal\Core\Config\ConfigFactoryInterface
  309. * The configuration factory service.
  310. */
  311. public static function configFactory() {
  312. return static::getContainer()->get('config.factory');
  313. }
  314. /**
  315. * Returns a queue for the given queue name.
  316. *
  317. * The following values can be set in your settings.php file's $settings
  318. * array to define which services are used for queues:
  319. * - queue_reliable_service_$name: The container service to use for the
  320. * reliable queue $name.
  321. * - queue_service_$name: The container service to use for the
  322. * queue $name.
  323. * - queue_default: The container service to use by default for queues
  324. * without overrides. This defaults to 'queue.database'.
  325. *
  326. * @param string $name
  327. * The name of the queue to work with.
  328. * @param bool $reliable
  329. * (optional) TRUE if the ordering of items and guaranteeing every item
  330. * executes at least once is important, FALSE if scalability is the main
  331. * concern. Defaults to FALSE.
  332. *
  333. * @return \Drupal\Core\Queue\QueueInterface
  334. * The queue object for a given name.
  335. */
  336. public static function queue($name, $reliable = FALSE) {
  337. return static::getContainer()->get('queue')->get($name, $reliable);
  338. }
  339. /**
  340. * Returns a key/value storage collection.
  341. *
  342. * @param string $collection
  343. * Name of the key/value collection to return.
  344. *
  345. * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
  346. */
  347. public static function keyValue($collection) {
  348. return static::getContainer()->get('keyvalue')->get($collection);
  349. }
  350. /**
  351. * Returns the state storage service.
  352. *
  353. * Use this to store machine-generated data, local to a specific environment
  354. * that does not need deploying and does not need human editing; for example,
  355. * the last time cron was run. Data which needs to be edited by humans and
  356. * needs to be the same across development, production, etc. environments
  357. * (for example, the system maintenance message) should use \Drupal::config() instead.
  358. *
  359. * @return \Drupal\Core\State\StateInterface
  360. */
  361. public static function state() {
  362. return static::getContainer()->get('state');
  363. }
  364. /**
  365. * Returns the default http client.
  366. *
  367. * @return \GuzzleHttp\ClientInterface
  368. * A guzzle http client instance.
  369. */
  370. public static function httpClient() {
  371. return static::getContainer()->get('http_client');
  372. }
  373. /**
  374. * Returns the entity query object for this entity type.
  375. *
  376. * @param string $entity_type
  377. * The entity type, e.g. node, for which the query object should be
  378. * returned.
  379. * @param string $conjunction
  380. * AND if all conditions in the query need to apply, OR if any of them is
  381. * enough. Optional, defaults to AND.
  382. *
  383. * @return \Drupal\Core\Entity\Query\QueryInterface
  384. * The query object that can query the given entity type.
  385. */
  386. public static function entityQuery($entity_type, $conjunction = 'AND') {
  387. return static::getContainer()->get('entity.query')->get($entity_type, $conjunction);
  388. }
  389. /**
  390. * Returns the entity query aggregate object for this entity type.
  391. *
  392. * @param string $entity_type
  393. * The entity type, e.g. node, for which the query object should be
  394. * returned.
  395. * @param string $conjunction
  396. * AND if all conditions in the query need to apply, OR if any of them is
  397. * enough. Optional, defaults to AND.
  398. *
  399. * @return \Drupal\Core\Entity\Query\QueryAggregateInterface
  400. * The query object that can query the given entity type.
  401. */
  402. public static function entityQueryAggregate($entity_type, $conjunction = 'AND') {
  403. return static::getContainer()->get('entity.query')->getAggregate($entity_type, $conjunction);
  404. }
  405. /**
  406. * Returns the flood instance.
  407. *
  408. * @return \Drupal\Core\Flood\FloodInterface
  409. */
  410. public static function flood() {
  411. return static::getContainer()->get('flood');
  412. }
  413. /**
  414. * Returns the module handler.
  415. *
  416. * @return \Drupal\Core\Extension\ModuleHandlerInterface
  417. */
  418. public static function moduleHandler() {
  419. return static::getContainer()->get('module_handler');
  420. }
  421. /**
  422. * Returns the typed data manager service.
  423. *
  424. * Use the typed data manager service for creating typed data objects.
  425. *
  426. * @return \Drupal\Core\TypedData\TypedDataManager
  427. * The typed data manager.
  428. *
  429. * @see \Drupal\Core\TypedData\TypedDataManager::create()
  430. */
  431. public static function typedDataManager() {
  432. return static::getContainer()->get('typed_data_manager');
  433. }
  434. /**
  435. * Returns the token service.
  436. *
  437. * @return \Drupal\Core\Utility\Token
  438. * The token service.
  439. */
  440. public static function token() {
  441. return static::getContainer()->get('token');
  442. }
  443. /**
  444. * Returns the url generator service.
  445. *
  446. * @return \Drupal\Core\Routing\UrlGeneratorInterface
  447. * The url generator service.
  448. */
  449. public static function urlGenerator() {
  450. return static::getContainer()->get('url_generator');
  451. }
  452. /**
  453. * Generates a URL string for a specific route based on the given parameters.
  454. *
  455. * This method is a convenience wrapper for generating URL strings for URLs
  456. * that have Drupal routes (that is, most pages generated by Drupal) using
  457. * the \Drupal\Core\Url object. See \Drupal\Core\Url::fromRoute() for
  458. * detailed documentation. For non-routed local URIs relative to
  459. * the base path (like robots.txt) use Url::fromUri()->toString() with the
  460. * base: scheme.
  461. *
  462. * @param string $route_name
  463. * The name of the route.
  464. * @param array $route_parameters
  465. * (optional) An associative array of parameter names and values.
  466. * @param array $options
  467. * (optional) An associative array of additional options.
  468. * @param bool $collect_cacheability_metadata
  469. * (optional) Defaults to FALSE. When TRUE, both the generated URL and its
  470. * associated cacheability metadata are returned.
  471. *
  472. * @return string|\Drupal\Core\GeneratedUrl
  473. * A string containing a URL to the given path.
  474. * When $collect_cacheability_metadata is TRUE, a GeneratedUrl object is
  475. * returned, containing the generated URL plus cacheability metadata.
  476. *
  477. * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
  478. * @see \Drupal\Core\Url
  479. * @see \Drupal\Core\Url::fromRoute()
  480. * @see \Drupal\Core\Url::fromUri()
  481. */
  482. public static function url($route_name, $route_parameters = array(), $options = array(), $collect_cacheability_metadata = FALSE) {
  483. return static::getContainer()->get('url_generator')->generateFromRoute($route_name, $route_parameters, $options, $collect_cacheability_metadata);
  484. }
  485. /**
  486. * Returns the link generator service.
  487. *
  488. * @return \Drupal\Core\Utility\LinkGeneratorInterface
  489. */
  490. public static function linkGenerator() {
  491. return static::getContainer()->get('link_generator');
  492. }
  493. /**
  494. * Renders a link with a given link text and Url object.
  495. *
  496. * This method is a convenience wrapper for the link generator service's
  497. * generate() method. For detailed documentation, see
  498. * \Drupal\Core\Routing\LinkGeneratorInterface::generate().
  499. *
  500. * @param string $text
  501. * The link text for the anchor tag.
  502. * @param \Drupal\Core\Url $url
  503. * The URL object used for the link.
  504. * @param bool $collect_cacheability_metadata
  505. * (optional) Defaults to FALSE. When TRUE, both the generated URL and its
  506. * associated cacheability metadata are returned.
  507. *
  508. * @return string|\Drupal\Core\GeneratedLink
  509. * An HTML string containing a link to the given route and parameters.
  510. * When $collect_cacheability_metadata is TRUE, a GeneratedLink object is
  511. * returned, containing the generated link plus cacheability metadata.
  512. *
  513. * @see \Drupal\Core\Utility\LinkGeneratorInterface::generate()
  514. * @see \Drupal\Core\Url
  515. */
  516. public static function l($text, Url $url, $collect_cacheability_metadata = FALSE) {
  517. return static::getContainer()->get('link_generator')->generate($text, $url, $collect_cacheability_metadata);
  518. }
  519. /**
  520. * Returns the string translation service.
  521. *
  522. * @return \Drupal\Core\StringTranslation\TranslationManager
  523. * The string translation manager.
  524. */
  525. public static function translation() {
  526. return static::getContainer()->get('string_translation');
  527. }
  528. /**
  529. * Returns the language manager service.
  530. *
  531. * @return \Drupal\Core\Language\LanguageManagerInterface
  532. * The language manager.
  533. */
  534. public static function languageManager() {
  535. return static::getContainer()->get('language_manager');
  536. }
  537. /**
  538. * Returns the CSRF token manager service.
  539. *
  540. * The generated token is based on the session ID of the current user. Normally,
  541. * anonymous users do not have a session, so the generated token will be
  542. * different on every page request. To generate a token for users without a
  543. * session, manually start a session prior to calling this function.
  544. *
  545. * @return \Drupal\Core\Access\CsrfTokenGenerator
  546. * The CSRF token manager.
  547. *
  548. * @see \Drupal\Core\Session\SessionManager::start()
  549. */
  550. public static function csrfToken() {
  551. return static::getContainer()->get('csrf_token');
  552. }
  553. /**
  554. * Returns the transliteration service.
  555. *
  556. * @return \Drupal\Core\Transliteration\PhpTransliteration
  557. * The transliteration manager.
  558. */
  559. public static function transliteration() {
  560. return static::getContainer()->get('transliteration');
  561. }
  562. /**
  563. * Returns the form builder service.
  564. *
  565. * @return \Drupal\Core\Form\FormBuilderInterface
  566. * The form builder.
  567. */
  568. public static function formBuilder() {
  569. return static::getContainer()->get('form_builder');
  570. }
  571. /**
  572. * Gets the theme service.
  573. *
  574. * @return \Drupal\Core\Theme\ThemeManagerInterface
  575. */
  576. public static function theme() {
  577. return static::getContainer()->get('theme.manager');
  578. }
  579. /**
  580. * Gets the syncing state.
  581. *
  582. * @return bool
  583. * Returns TRUE is syncing flag set.
  584. */
  585. public static function isConfigSyncing() {
  586. return static::getContainer()->get('config.installer')->isSyncing();
  587. }
  588. /**
  589. * Returns a channel logger object.
  590. *
  591. * @param string $channel
  592. * The name of the channel. Can be any string, but the general practice is
  593. * to use the name of the subsystem calling this.
  594. *
  595. * @return \Psr\Log\LoggerInterface
  596. * The logger for this channel.
  597. */
  598. public static function logger($channel) {
  599. return static::getContainer()->get('logger.factory')->get($channel);
  600. }
  601. /**
  602. * Returns the menu tree.
  603. *
  604. * @return \Drupal\Core\Menu\MenuLinkTreeInterface
  605. * The menu tree.
  606. */
  607. public static function menuTree() {
  608. return static::getContainer()->get('menu.link_tree');
  609. }
  610. /**
  611. * Returns the path validator.
  612. *
  613. * @return \Drupal\Core\Path\PathValidatorInterface
  614. */
  615. public static function pathValidator() {
  616. return static::getContainer()->get('path.validator');
  617. }
  618. /**
  619. * Returns the access manager service.
  620. *
  621. * @return \Drupal\Core\Access\AccessManagerInterface
  622. * The access manager service.
  623. */
  624. public static function accessManager() {
  625. return static::getContainer()->get('access_manager');
  626. }
  627. /**
  628. * Returns the redirect destination helper.
  629. *
  630. * @return \Drupal\Core\Routing\RedirectDestinationInterface
  631. * The redirect destination helper.
  632. */
  633. public static function destination() {
  634. return static::getContainer()->get('redirect.destination');
  635. }
  636. }

Classes

Namesort descending Description
Drupal Static Service Container wrapper.