Drupal.php

You are here

Contains Drupal.

Classes

Namesort descending Description
Drupal Static Service Container wrapper.

File

core/lib/Drupal.php
View source
  1. <?php
  2. /**
  3. * @file
  4. * Contains Drupal.
  5. */
  6. use Symfony\Component\DependencyInjection\ContainerInterface;
  7. /**
  8. * Static Service Container wrapper.
  9. *
  10. * Generally, code in Drupal should accept its dependencies via either
  11. * constructor injection or setter method injection. However, there are cases,
  12. * particularly in legacy procedural code, where that is infeasible. This
  13. * class acts as a unified global accessor to arbitrary services within the
  14. * system in order to ease the transition from procedural code to injected OO
  15. * code.
  16. *
  17. * The container is built by the kernel and passed in to this class which stores
  18. * it statically. The container always contains the services from
  19. * \Drupal\Core\CoreServiceProvider, the service providers of enabled modules and any other
  20. * service providers defined in $GLOBALS['conf']['container_service_providers'].
  21. *
  22. * This class exists only to support legacy code that cannot be dependency
  23. * injected. If your code needs it, consider refactoring it to be object
  24. * oriented, if possible. When this is not possible, for instance in the case of
  25. * hook implementations, and your code is more than a few non-reusable lines, it
  26. * is recommended to instantiate an object implementing the actual logic.
  27. *
  28. * @code
  29. * // Legacy procedural code.
  30. * function hook_do_stuff() {
  31. * $lock = lock()->acquire('stuff_lock');
  32. * // ...
  33. * }
  34. *
  35. * // Correct procedural code.
  36. * function hook_do_stuff() {
  37. * $lock = \Drupal::lock()->acquire('stuff_lock');
  38. * // ...
  39. * }
  40. *
  41. * // The preferred way: dependency injected code.
  42. * function hook_do_stuff() {
  43. * // Move the actual implementation to a class and instantiate it.
  44. * $instance = new StuffDoingClass(\Drupal::lock());
  45. * $instance->doStuff();
  46. *
  47. * // Or, even better, rely on the service container to avoid hard coding a
  48. * // specific interface implementation, so that the actual logic can be
  49. * // swapped. This might not always make sense, but in general it is a good
  50. * // practice.
  51. * \Drupal::service('stuff.doing')->doStuff();
  52. * }
  53. *
  54. * interface StuffDoingInterface {
  55. * public function doStuff();
  56. * }
  57. *
  58. * class StuffDoingClass implements StuffDoingInterface {
  59. * protected $lockBackend;
  60. *
  61. * public function __construct(LockBackendInterface $lockBackend) {
  62. * $this->lockBackend = $lockBackend;
  63. * }
  64. *
  65. * public function doStuff() {
  66. * $lock = $this->lockBackend->acquire('stuff_lock');
  67. * // ...
  68. * }
  69. * }
  70. * @endcode
  71. *
  72. * @see \Drupal\Core\DrupalKernel
  73. */
  74. class Drupal {
  75. /**
  76. * The current system version.
  77. */
  78. const VERSION = '8.0-dev';
  79. /**
  80. * Core API compatibility.
  81. */
  82. const CORE_COMPATIBILITY = '8.x';
  83. /**
  84. * Core minimum schema version.
  85. */
  86. const CORE_MINIMUM_SCHEMA_VERSION = 8000;
  87. /**
  88. * The currently active container object.
  89. *
  90. * @var \Symfony\Component\DependencyInjection\ContainerInterface
  91. */
  92. protected static $container;
  93. /**
  94. * Sets a new global container.
  95. *
  96. * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
  97. * A new container instance to replace the current. NULL may be passed by
  98. * testing frameworks to ensure that the global state of a previous
  99. * environment does not leak into a test.
  100. */
  101. public static function setContainer(ContainerInterface $container = NULL) {
  102. static::$container = $container;
  103. }
  104. /**
  105. * Returns the currently active global container.
  106. *
  107. * @deprecated This method is only useful for the testing environment. It
  108. * should not be used otherwise.
  109. *
  110. * @return \Symfony\Component\DependencyInjection\ContainerInterface
  111. */
  112. public static function getContainer() {
  113. return static::$container;
  114. }
  115. /**
  116. * Retrieves a service from the container.
  117. *
  118. * Use this method if the desired service is not one of those with a dedicated
  119. * accessor method below. If it is listed below, those methods are preferred
  120. * as they can return useful type hints.
  121. *
  122. * @param string $id
  123. * The ID of the service to retrieve.
  124. * @return mixed
  125. * The specified service.
  126. */
  127. public static function service($id) {
  128. return static::$container->get($id);
  129. }
  130. /**
  131. * Indicates if a service is defined in the container.
  132. *
  133. * @param string $id
  134. * The ID of the service to check.
  135. *
  136. * @return bool
  137. * TRUE if the specified service exists, FALSE otherwise.
  138. */
  139. public static function hasService($id) {
  140. return static::$container && static::$container->has($id);
  141. }
  142. /**
  143. * Indicates if there is a currently active request object.
  144. *
  145. * @return bool
  146. * TRUE if there is a currently active request object, FALSE otherwise.
  147. */
  148. public static function hasRequest() {
  149. return static::$container && static::$container->has('request') && static::$container->initialized('request') && static::$container->isScopeActive('request');
  150. }
  151. /**
  152. * Retrieves the currently active request object.
  153. *
  154. * Note: The use of this wrapper in particular is especially discouraged. Most
  155. * code should not need to access the request directly. Doing so means it
  156. * will only function when handling an HTTP request, and will require special
  157. * modification or wrapping when run from a command line tool, from certain
  158. * queue processors, or from automated tests.
  159. *
  160. * If code must access the request, it is considerably better to register
  161. * an object with the Service Container and give it a setRequest() method
  162. * that is configured to run when the service is created. That way, the
  163. * correct request object can always be provided by the container and the
  164. * service can still be unit tested.
  165. *
  166. * If this method must be used, never save the request object that is
  167. * returned. Doing so may lead to inconsistencies as the request object is
  168. * volatile and may change at various times, such as during a subrequest.
  169. *
  170. * @return \Symfony\Component\HttpFoundation\Request
  171. * The currently active request object.
  172. */
  173. public static function request() {
  174. return static::$container->get('request');
  175. }
  176. /**
  177. * Gets the current active user.
  178. *
  179. * @return \Drupal\Core\Session\AccountProxyInterface
  180. */
  181. public static function currentUser() {
  182. return static::$container->get('current_user');
  183. }
  184. /**
  185. * Retrieves the entity manager service.
  186. *
  187. * @return \Drupal\Core\Entity\EntityManagerInterface
  188. * The entity manager service.
  189. */
  190. public static function entityManager() {
  191. return static::$container->get('entity.manager');
  192. }
  193. /**
  194. * Returns the current primary database.
  195. *
  196. * @return \Drupal\Core\Database\Connection
  197. * The current active database's master connection.
  198. */
  199. public static function database() {
  200. return static::$container->get('database');
  201. }
  202. /**
  203. * Returns the requested cache bin.
  204. *
  205. * @param string $bin
  206. * (optional) The cache bin for which the cache object should be returned,
  207. * defaults to 'default'.
  208. *
  209. * @return \Drupal\Core\Cache\CacheBackendInterface
  210. * The cache object associated with the specified bin.
  211. *
  212. * @ingroup cache
  213. */
  214. public static function cache($bin = 'default') {
  215. return static::$container->get('cache.' . $bin);
  216. }
  217. /**
  218. * Returns an expirable key value store collection.
  219. *
  220. * @param string $collection
  221. * The name of the collection holding key and value pairs.
  222. *
  223. * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
  224. * An expirable key value store collection.
  225. */
  226. public static function keyValueExpirable($collection) {
  227. return static::$container->get('keyvalue.expirable')->get($collection);
  228. }
  229. /**
  230. * Returns the locking layer instance.
  231. *
  232. * @return \Drupal\Core\Lock\LockBackendInterface
  233. *
  234. * @ingroup lock
  235. */
  236. public static function lock() {
  237. return static::$container->get('lock');
  238. }
  239. /**
  240. * Retrieves a configuration object.
  241. *
  242. * This is the main entry point to the configuration API. Calling
  243. * @code \Drupal::config('book.admin') @endcode will return a configuration
  244. * object in which the book module can store its administrative settings.
  245. *
  246. * @param string $name
  247. * The name of the configuration object to retrieve. The name corresponds to
  248. * a configuration file. For @code \Drupal::config('book.admin') @endcode, the config
  249. * object returned will contain the contents of book.admin configuration file.
  250. *
  251. * @return \Drupal\Core\Config\Config
  252. * A configuration object.
  253. */
  254. public static function config($name) {
  255. return static::$container->get('config.factory')->get($name);
  256. }
  257. /**
  258. * Retrieves the configuration factory.
  259. *
  260. * This is mostly used to change the override settings on the configuration
  261. * factory. For example, changing the language, or turning all overrides on
  262. * or off.
  263. *
  264. * @return \Drupal\Core\Config\ConfigFactoryInterface
  265. * The configuration factory service.
  266. */
  267. public static function configFactory() {
  268. return static::$container->get('config.factory');
  269. }
  270. /**
  271. * Returns a queue for the given queue name.
  272. *
  273. * The following values can be set in your settings.php file's $settings
  274. * array to define which services are used for queues:
  275. * - queue_reliable_service_$name: The container service to use for the
  276. * reliable queue $name.
  277. * - queue_service_$name: The container service to use for the
  278. * queue $name.
  279. * - queue_default: The container service to use by default for queues
  280. * without overrides. This defaults to 'queue.database'.
  281. *
  282. * @param string $name
  283. * The name of the queue to work with.
  284. * @param bool $reliable
  285. * (optional) TRUE if the ordering of items and guaranteeing every item
  286. * executes at least once is important, FALSE if scalability is the main
  287. * concern. Defaults to FALSE.
  288. *
  289. * @return \Drupal\Core\Queue\QueueInterface
  290. * The queue object for a given name.
  291. */
  292. public static function queue($name, $reliable = FALSE) {
  293. return static::$container->get('queue')->get($name, $reliable);
  294. }
  295. /**
  296. * Returns a key/value storage collection.
  297. *
  298. * @param string $collection
  299. * Name of the key/value collection to return.
  300. *
  301. * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
  302. */
  303. public static function keyValue($collection) {
  304. return static::$container->get('keyvalue')->get($collection);
  305. }
  306. /**
  307. * Returns the state storage service.
  308. *
  309. * Use this to store machine-generated data, local to a specific environment
  310. * that does not need deploying and does not need human editing; for example,
  311. * the last time cron was run. Data which needs to be edited by humans and
  312. * needs to be the same across development, production, etc. environments
  313. * (for example, the system maintenance message) should use \Drupal::config() instead.
  314. *
  315. * @return \Drupal\Core\State\StateInterface
  316. */
  317. public static function state() {
  318. return static::$container->get('state');
  319. }
  320. /**
  321. * Returns the default http client.
  322. *
  323. * @return \GuzzleHttp\ClientInterface
  324. * A guzzle http client instance.
  325. */
  326. public static function httpClient() {
  327. return static::$container->get('http_client');
  328. }
  329. /**
  330. * Returns the entity query object for this entity type.
  331. *
  332. * @param string $entity_type
  333. * The entity type, e.g. node, for which the query object should be
  334. * returned.
  335. * @param string $conjunction
  336. * AND if all conditions in the query need to apply, OR if any of them is
  337. * enough. Optional, defaults to AND.
  338. *
  339. * @return \Drupal\Core\Entity\Query\QueryInterface
  340. * The query object that can query the given entity type.
  341. */
  342. public static function entityQuery($entity_type, $conjunction = 'AND') {
  343. return static::$container->get('entity.query')->get($entity_type, $conjunction);
  344. }
  345. /**
  346. * Returns the entity query aggregate object for this entity type.
  347. *
  348. * @param string $entity_type
  349. * The entity type, e.g. node, for which the query object should be
  350. * returned.
  351. * @param string $conjunction
  352. * AND if all conditions in the query need to apply, OR if any of them is
  353. * enough. Optional, defaults to AND.
  354. *
  355. * @return \Drupal\Core\Entity\Query\QueryAggregateInterface
  356. * The query object that can query the given entity type.
  357. */
  358. public static function entityQueryAggregate($entity_type, $conjunction = 'AND') {
  359. return static::$container->get('entity.query')->getAggregate($entity_type, $conjunction);
  360. }
  361. /**
  362. * Returns the flood instance.
  363. *
  364. * @return \Drupal\Core\Flood\FloodInterface
  365. */
  366. public static function flood() {
  367. return static::$container->get('flood');
  368. }
  369. /**
  370. * Returns the module handler.
  371. *
  372. * @return \Drupal\Core\Extension\ModuleHandlerInterface
  373. */
  374. public static function moduleHandler() {
  375. return static::$container->get('module_handler');
  376. }
  377. /**
  378. * Returns the typed data manager service.
  379. *
  380. * Use the typed data manager service for creating typed data objects.
  381. *
  382. * @return \Drupal\Core\TypedData\TypedDataManager
  383. * The typed data manager.
  384. *
  385. * @see \Drupal\Core\TypedData\TypedDataManager::create()
  386. */
  387. public static function typedDataManager() {
  388. return static::$container->get('typed_data_manager');
  389. }
  390. /**
  391. * Returns the token service.
  392. *
  393. * @return \Drupal\Core\Utility\Token
  394. * The token service.
  395. */
  396. public static function token() {
  397. return static::$container->get('token');
  398. }
  399. /**
  400. * Returns the url generator service.
  401. *
  402. * @return \Drupal\Core\Routing\UrlGeneratorInterface
  403. * The url generator service.
  404. */
  405. public static function urlGenerator() {
  406. return static::$container->get('url_generator');
  407. }
  408. /**
  409. * Generates a URL or path for a specific route based on the given parameters.
  410. *
  411. * Parameters that reference placeholders in the route pattern will be
  412. * substituted for them in the pattern. Extra params are added as query
  413. * strings to the URL.
  414. *
  415. * @param string $route_name
  416. * The name of the route
  417. * @param array $route_parameters
  418. * An associative array of parameter names and values.
  419. * @param array $options
  420. * (optional) An associative array of additional options, with the following
  421. * elements:
  422. * - 'query': An array of query key/value-pairs (without any URL-encoding)
  423. * to append to the URL. Merged with the parameters array.
  424. * - 'fragment': A fragment identifier (named anchor) to append to the URL.
  425. * Do not include the leading '#' character.
  426. * - 'absolute': Defaults to FALSE. Whether to force the output to be an
  427. * absolute link (beginning with http:). Useful for links that will be
  428. * displayed outside the site, such as in an RSS feed.
  429. * - 'language': An optional language object used to look up the alias
  430. * for the URL. If $options['language'] is omitted, the language will be
  431. * obtained from \Drupal::languageManager()->getCurrentLanguage(Language::TYPE_URL).
  432. * - 'https': Whether this URL should point to a secure location. If not
  433. * defined, the current scheme is used, so the user stays on HTTP or HTTPS
  434. * respectively. if mixed mode sessions are permitted, TRUE enforces HTTPS
  435. * and FALSE enforces HTTP.
  436. *
  437. * @return string
  438. * The generated URL for the given route.
  439. *
  440. * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
  441. * Thrown when the named route doesn't exist.
  442. * @throws \Symfony\Component\Routing\Exception\MissingMandatoryParametersException
  443. * Thrown when some parameters are missing that are mandatory for the route.
  444. * @throws \Symfony\Component\Routing\Exception\InvalidParameterException
  445. * Thrown when a parameter value for a placeholder is not correct because it
  446. * does not match the requirement.
  447. *
  448. * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
  449. */
  450. public static function url($route_name, $route_parameters = array(), $options = array()) {
  451. return static::$container->get('url_generator')->generateFromRoute($route_name, $route_parameters, $options);
  452. }
  453. /**
  454. * Returns the link generator service.
  455. *
  456. * @return \Drupal\Core\Utility\LinkGeneratorInterface
  457. */
  458. public static function linkGenerator() {
  459. return static::$container->get('link_generator');
  460. }
  461. /**
  462. * Renders a link to a route given a route name and its parameters.
  463. *
  464. * This function correctly handles aliased paths and sanitizing text, so all
  465. * internal links output by modules should be generated by this function if
  466. * possible.
  467. *
  468. * However, for links enclosed in translatable text you should use t() and
  469. * embed the HTML anchor tag directly in the translated string. For example:
  470. * @code
  471. * t('Visit the <a href="@url">content types</a> page', array('@url' => \Drupal::url('node.overview_types')));
  472. * @endcode
  473. * This keeps the context of the link title ('settings' in the example) for
  474. * translators.
  475. *
  476. * @param string|array $text
  477. * The link text for the anchor tag as a translated string or render array.
  478. * @param string $route_name
  479. * The name of the route to use to generate the link.
  480. * @param array $parameters
  481. * (optional) Any parameters needed to render the route path pattern.
  482. * @param array $options
  483. * (optional) An associative array of additional options. Defaults to an
  484. * empty array. It may contain the following elements:
  485. * - 'query': An array of query key/value-pairs (without any URL-encoding) to
  486. * append to the URL.
  487. * - absolute: Whether to force the output to be an absolute link (beginning
  488. * with http:). Useful for links that will be displayed outside the site,
  489. * such as in an RSS feed. Defaults to FALSE.
  490. * - attributes: An associative array of HTML attributes to apply to the
  491. * anchor tag. If element 'class' is included, it must be an array; 'title'
  492. * must be a string; other elements are more flexible, as they just need
  493. * to work as an argument for the constructor of the class
  494. * Drupal\Core\Template\Attribute($options['attributes']).
  495. * - html: Whether $text is HTML or just plain-text. For
  496. * example, to make an image tag into a link, this must be set to TRUE, or
  497. * you will see the escaped HTML image tag. $text is not sanitized if
  498. * 'html' is TRUE. The calling function must ensure that $text is already
  499. * safe. Defaults to FALSE.
  500. * - language: An optional language object. If the path being linked to is
  501. * internal to the site, $options['language'] is used to determine whether
  502. * the link is "active", or pointing to the current page (the language as
  503. * well as the path must match).
  504. *
  505. * @return string
  506. * An HTML string containing a link to the given route and parameters.
  507. *
  508. * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
  509. * Thrown when the named route doesn't exist.
  510. * @throws \Symfony\Component\Routing\Exception\MissingMandatoryParametersException
  511. * Thrown when some parameters are missing that are mandatory for the route.
  512. * @throws \Symfony\Component\Routing\Exception\InvalidParameterException
  513. * Thrown when a parameter value for a placeholder is not correct because it
  514. * does not match the requirement.
  515. *
  516. * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
  517. * @see \Drupal\Core\Utility\LinkGeneratorInterface::generate()
  518. */
  519. public static function l($text, $route_name, array $parameters = array(), array $options = array()) {
  520. return static::$container->get('link_generator')->generate($text, $route_name, $parameters, $options);
  521. }
  522. /**
  523. * Returns the string translation service.
  524. *
  525. * @return \Drupal\Core\StringTranslation\TranslationManager
  526. * The string translation manager.
  527. */
  528. public static function translation() {
  529. return static::$container->get('string_translation');
  530. }
  531. /**
  532. * Returns the language manager service.
  533. *
  534. * @return \Drupal\Core\Language\LanguageManagerInterface
  535. * The language manager.
  536. */
  537. public static function languageManager() {
  538. return static::$container->get('language_manager');
  539. }
  540. /**
  541. * Returns the CSRF token manager service.
  542. *
  543. * The generated token is based on the session ID of the current user. Normally,
  544. * anonymous users do not have a session, so the generated token will be
  545. * different on every page request. To generate a token for users without a
  546. * session, manually start a session prior to calling this function.
  547. *
  548. * @return \Drupal\Core\Access\CsrfTokenGenerator
  549. * The CSRF token manager.
  550. *
  551. * @see \Drupal\Core\Session\SessionManager::start()
  552. */
  553. public static function csrfToken() {
  554. return static::$container->get('csrf_token');
  555. }
  556. /**
  557. * Returns the transliteration service.
  558. *
  559. * @return \Drupal\Core\Transliteration\PHPTransliteration
  560. * The transliteration manager.
  561. */
  562. public static function transliteration() {
  563. return static::$container->get('transliteration');
  564. }
  565. /**
  566. * Returns the form builder service.
  567. *
  568. * @return \Drupal\Core\Form\FormBuilderInterface
  569. * The form builder.
  570. */
  571. public static function formBuilder() {
  572. return static::$container->get('form_builder');
  573. }
  574. /**
  575. * Gets the syncing state.
  576. *
  577. * @return bool
  578. * Returns TRUE is syncing flag set.
  579. */
  580. public function isConfigSyncing() {
  581. return static::$container->get('config.installer')->isSyncing();
  582. }
  583. }