core.api.php 124 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651
  1. <?php
  2. /**
  3. * @file
  4. * Documentation landing page and topics, plus core library hooks.
  5. */
  6. /**
  7. * @mainpage
  8. * Welcome to the Drupal API Documentation!
  9. *
  10. * This site is an API reference for Drupal, generated from comments embedded
  11. * in the source code. More in-depth documentation can be found at
  12. * https://www.drupal.org/developing/api.
  13. *
  14. * Here are some topics to help you get started developing with Drupal.
  15. *
  16. * @section essentials Essential background concepts
  17. *
  18. * - @link oo_conventions Object-oriented conventions used in Drupal @endlink
  19. * - @link extending Extending and altering Drupal @endlink
  20. * - @link best_practices Security and best practices @endlink
  21. * - @link info_types Types of information in Drupal @endlink
  22. *
  23. * @section interface User interface
  24. *
  25. * - @link menu Menu entries, local tasks, and other links @endlink
  26. * - @link routing Routing API and page controllers @endlink
  27. * - @link form_api Forms @endlink
  28. * - @link block_api Blocks @endlink
  29. * - @link ajax Ajax @endlink
  30. *
  31. * @section store_retrieve Storing and retrieving data
  32. *
  33. * - @link entity_api Entities @endlink
  34. * - @link field Fields @endlink
  35. * - @link config_api Configuration API @endlink
  36. * - @link state_api State API @endlink
  37. * - @link views_overview Views @endlink
  38. * - @link database Database abstraction layer @endlink
  39. *
  40. * @section other_essentials Other essential APIs
  41. *
  42. * - @link plugin_api Plugins @endlink
  43. * - @link container Services and the Dependency Injection Container @endlink
  44. * - @link events Events @endlink
  45. * - @link i18n Internationalization @endlink
  46. * - @link cache Caching @endlink
  47. * - @link utility Utility classes and functions @endlink
  48. * - @link user_api User accounts, permissions, and roles @endlink
  49. * - @link theme_render Render API @endlink
  50. * - @link themeable Theme system @endlink
  51. * - @link update_api Update API @endlink
  52. * - @link migration Migration @endlink
  53. *
  54. * @section additional Additional topics
  55. *
  56. * - @link batch Batch API @endlink
  57. * - @link queue Queue API @endlink
  58. * - @link typed_data Typed Data @endlink
  59. * - @link testing Automated tests @endlink
  60. * - @link php_assert PHP Runtime Assert Statements @endlink
  61. * - @link third_party Integrating third-party applications @endlink
  62. *
  63. * @section more_info Further information
  64. *
  65. * - @link https://api.drupal.org/api/drupal/groups/8 All topics @endlink
  66. * - @link https://www.drupal.org/project/examples Examples project (sample modules) @endlink
  67. * - @link https://www.drupal.org/list-changes API change notices @endlink
  68. * - @link https://www.drupal.org/developing/api/8 Drupal 8 API longer references @endlink
  69. */
  70. /**
  71. * @defgroup third_party REST and Application Integration
  72. * @{
  73. * Integrating third-party applications using REST and related operations.
  74. *
  75. * @section sec_overview Overview of web services
  76. * Web services make it possible for applications and web sites to read and
  77. * update information from other web sites. There are several standard
  78. * techniques for providing web services, including:
  79. * - SOAP: http://wikipedia.org/wiki/SOAP
  80. * - XML-RPC: http://wikipedia.org/wiki/XML-RPC
  81. * - REST: http://wikipedia.org/wiki/Representational_state_transfer
  82. * Drupal sites can both provide web services and integrate third-party web
  83. * services.
  84. *
  85. * @section sec_rest_overview Overview of REST
  86. * The REST technique uses basic HTTP requests to obtain and update data, where
  87. * each web service defines a specific API (HTTP GET and/or POST parameters and
  88. * returned response) for its HTTP requests. REST requests are separated into
  89. * several types, known as methods, including:
  90. * - GET: Requests to obtain data.
  91. * - POST: Requests to update or create data.
  92. * - PUT: Requests to update or create data (limited support, currently unused
  93. * by entity resources).
  94. * - PATCH: Requests to update a subset of data, such as one field.
  95. * - DELETE: Requests to delete data.
  96. * The Drupal Core REST module provides support for GET, POST, PATCH, and DELETE
  97. * quests on entities, GET requests on the database log from the Database
  98. * Logging module, and a plugin framework for providing REST support for other
  99. * data and other methods.
  100. *
  101. * REST requests can be authenticated. The Drupal Core Basic Auth module
  102. * provides authentication using the HTTP Basic protocol; the contributed module
  103. * OAuth (https://www.drupal.org/project/oauth) implements the OAuth
  104. * authentication protocol. You can also use cookie-based authentication, which
  105. * would require users to be logged into the Drupal site while using the
  106. * application on the third-party site that is using the REST service.
  107. *
  108. * @section sec_rest Enabling REST for entities and the log
  109. * Here are the steps to take to use the REST operations provided by Drupal
  110. * Core:
  111. * - Enable the REST module, plus Basic Auth (or another authentication method)
  112. * and HAL.
  113. * - Node entity support is configured by default. If you would like to support
  114. * other types of entities, you can copy
  115. * core/modules/rest/config/install/rest.settings.yml to your sync
  116. * configuration directory, appropriately modified for other entity types,
  117. * and import it. Support for GET on the log from the Database Logging module
  118. * can also be enabled in this way; in this case, the 'entity:node' line
  119. * in the configuration would be replaced by the appropriate plugin ID,
  120. * 'dblog'.
  121. * - Set up permissions to allow the desired REST operations for a role, and set
  122. * up one or more user accounts to perform the operations.
  123. * - To perform a REST operation, send a request to either the canonical URL
  124. * for an entity (such as node/12345 for a node), or if the entity does not
  125. * have a canonical URL, a URL like entity/(type)/(ID). The URL for a log
  126. * entry is dblog/(ID). The request must have the following properties:
  127. * - The request method must be set to the REST method you are using (POST,
  128. * GET, PATCH, etc.).
  129. * - The content type for the data you send, or the accept type for the
  130. * data you are receiving, must be set to 'application/hal+json'.
  131. * - If you are sending data, it must be JSON-encoded.
  132. * - You'll also need to make sure the authentication information is sent
  133. * with the request, unless you have allowed access to anonymous users.
  134. *
  135. * For more detailed information on setting up REST, see
  136. * https://www.drupal.org/documentation/modules/rest.
  137. *
  138. * @section sec_plugins Defining new REST plugins
  139. * The REST framework in the REST module has support built in for entities, but
  140. * it is also an extensible plugin-based system. REST plugins implement
  141. * interface \Drupal\rest\Plugin\ResourceInterface, and generally extend base
  142. * class \Drupal\rest\Plugin\ResourceBase. They are annotated with
  143. * \Drupal\rest\Annotation\RestResource annotation, and must be in plugin
  144. * namespace subdirectory Plugin\rest\resource. For more information on how to
  145. * create plugins, see the @link plugin_api Plugin API topic. @endlink
  146. *
  147. * If you create a new REST plugin, you will also need to enable it by
  148. * providing default configuration or configuration import, as outlined in
  149. * @ref sec_rest above.
  150. *
  151. * @section sec_integrate Integrating data from other sites into Drupal
  152. * If you want to integrate data from other web sites into Drupal, here are
  153. * some notes:
  154. * - There are contributed modules available for integrating many third-party
  155. * sites into Drupal. Search on https://www.drupal.org/project/project_module
  156. * - If there is not an existing module, you will need to find documentation on
  157. * the specific web services API for the site you are trying to integrate.
  158. * - There are several classes and functions that are useful for interacting
  159. * with web services:
  160. * - You should make requests using the 'http_client' service, which
  161. * implements \GuzzleHttp\ClientInterface. See the
  162. * @link container Services topic @endlink for more information on
  163. * services. If you cannot use dependency injection to retrieve this
  164. * service, the \Drupal::httpClient() method is available. A good example
  165. * of how to use this service can be found in
  166. * \Drupal\aggregator\Plugin\aggregator\fetcher\DefaultFetcher
  167. * - \Drupal\Component\Serialization\Json (JSON encoding and decoding).
  168. * - PHP has functions and classes for parsing XML; see
  169. * http://php.net/manual/refs.xml.php
  170. * @}
  171. */
  172. /**
  173. * @defgroup state_api State API
  174. * @{
  175. * Information about the State API.
  176. *
  177. * The State API is one of several methods in Drupal for storing information.
  178. * See the @link info_types Information types topic @endlink for an
  179. * overview of the different types of information.
  180. *
  181. * The basic entry point into the State API is \Drupal::state(), which returns
  182. * an object of class \Drupal\Core\State\StateInterface. This class has
  183. * methods for storing and retrieving state information; each piece of state
  184. * information is associated with a string-valued key. Example:
  185. * @code
  186. * // Get the state class.
  187. * $state = \Drupal::state();
  188. * // Find out when cron was last run; the key is 'system.cron_last'.
  189. * $time = $state->get('system.cron_last');
  190. * // Set the cron run time to the current request time.
  191. * $state->set('system.cron_last', REQUEST_TIME);
  192. * @endcode
  193. *
  194. * For more on the State API, see https://www.drupal.org/developing/api/8/state
  195. * @}
  196. */
  197. /**
  198. * @defgroup config_api Configuration API
  199. * @{
  200. * Information about the Configuration API.
  201. *
  202. * The Configuration API is one of several methods in Drupal for storing
  203. * information. See the @link info_types Information types topic @endlink for
  204. * an overview of the different types of information. The sections below have
  205. * more information about the configuration API; see
  206. * https://www.drupal.org/developing/api/8/configuration for more details.
  207. *
  208. * @section sec_storage Configuration storage
  209. * In Drupal, there is a concept of the "active" configuration, which is the
  210. * configuration that is currently in use for a site. The storage used for the
  211. * active configuration is configurable: it could be in the database, in files
  212. * in a particular directory, or in other storage backends; the default storage
  213. * is in the database. Module developers must use the configuration API to
  214. * access the active configuration, rather than being concerned about the
  215. * details of where and how it is stored.
  216. *
  217. * Configuration is divided into individual objects, each of which has a
  218. * unique name or key. Some modules will have only one configuration object,
  219. * typically called 'mymodule.settings'; some modules will have many. Within
  220. * a configuration object, configuration settings have data types (integer,
  221. * string, Boolean, etc.) and settings can also exist in a nested hierarchy,
  222. * known as a "mapping".
  223. *
  224. * Configuration can also be overridden on a global, per-language, or
  225. * per-module basis. See https://www.drupal.org/node/1928898 for more
  226. * information.
  227. *
  228. * @section sec_yaml Configuration YAML files
  229. * Whether or not configuration files are being used for the active
  230. * configuration storage on a particular site, configuration files are always
  231. * used for:
  232. * - Defining the default configuration for an extension (module, theme, or
  233. * profile), which is imported to the active storage when the extension is
  234. * enabled. These configuration items are located in the config/install
  235. * sub-directory of the extension. Note that changes to this configuration
  236. * after a module or theme is already enabled have no effect; to make a
  237. * configuration change after a module or theme is enabled, you would need to
  238. * uninstall/reinstall or use a hook_update_N() function.
  239. * - Defining optional configuration for a module or theme. Optional
  240. * configuration items are located in the config/optional sub-directory of the
  241. * extension. These configuration items have dependencies that are not
  242. * explicit dependencies of the extension, so they are only installed if all
  243. * dependencies are met. For example, in the scenario that module A defines a
  244. * dependency which requires module B, but module A is installed first and
  245. * module B some time later, then module A's config/optional directory will be
  246. * scanned at that time for newly met dependencies, and the configuration will
  247. * be installed then. If module B is never installed, the configuration item
  248. * will not be installed either.
  249. * - Exporting and importing configuration.
  250. *
  251. * The file storage format for configuration information in Drupal is
  252. * @link http://wikipedia.org/wiki/YAML YAML files. @endlink Configuration is
  253. * divided into files, each containing one configuration object. The file name
  254. * for a configuration object is equal to the unique name of the configuration,
  255. * with a '.yml' extension. The default configuration files for each module are
  256. * placed in the config/install directory under the top-level module directory,
  257. * so look there in most Core modules for examples.
  258. *
  259. * @section sec_schema Configuration schema and translation
  260. * Each configuration file has a specific structure, which is expressed as a
  261. * YAML-based configuration schema. The configuration schema details the
  262. * structure of the configuration, its data types, and which of its values need
  263. * to be translatable. Each module needs to define its configuration schema in
  264. * files in the config/schema directory under the top-level module directory, so
  265. * look there in most Core modules for examples.
  266. *
  267. * Configuration can be internationalized; see the
  268. * @link i18n Internationalization topic @endlink for more information. Data
  269. * types label, text, and date_format in configuration schema are translatable;
  270. * string is non-translatable text (the 'translatable' property on a schema
  271. * data type definition indicates that it is translatable).
  272. *
  273. * @section sec_simple Simple configuration
  274. * The simple configuration API should be used for information that will always
  275. * have exactly one copy or version. For instance, if your module has a
  276. * setting that is either on or off, then this is only defined once, and it
  277. * would be a Boolean-valued simple configuration setting.
  278. *
  279. * The first task in using the simple configuration API is to define the
  280. * configuration file structure, file name, and schema of your settings (see
  281. * @ref sec_yaml above). Once you have done that, you can retrieve the active
  282. * configuration object that corresponds to configuration file mymodule.foo.yml
  283. * with a call to:
  284. * @code
  285. * $config = \Drupal::config('mymodule.foo');
  286. * @endcode
  287. *
  288. * This will be an object of class \Drupal\Core\Config\Config, which has methods
  289. * for getting configuration information. For instance, if your YAML file
  290. * structure looks like this:
  291. * @code
  292. * enabled: '0'
  293. * bar:
  294. * baz: 'string1'
  295. * boo: 34
  296. * @endcode
  297. * you can make calls such as:
  298. * @code
  299. * // Get a single value.
  300. * $enabled = $config->get('enabled');
  301. * // Get an associative array.
  302. * $bar = $config->get('bar');
  303. * // Get one element of the array.
  304. * $bar_baz = $config->get('bar.baz');
  305. * @endcode
  306. *
  307. * The Config object that was obtained and used in the previous examples does
  308. * not allow you to change configuration. If you want to change configuration,
  309. * you will instead need to get the Config object by making a call to
  310. * getEditable() on the config factory:
  311. * @code
  312. * $config =\Drupal::service('config.factory')->getEditable('mymodule.foo');
  313. * @endcode
  314. *
  315. * Individual configuration values can be changed or added using the set()
  316. * method and saved using the save() method:
  317. * @code
  318. * // Set a scalar value.
  319. * $config->set('enabled', 1);
  320. * // Save the configuration.
  321. * $config->save();
  322. * @endcode
  323. *
  324. * Configuration values can also be unset using the clear() method, which is
  325. * also chainable:
  326. * @code
  327. * $config->clear('bar.boo')->save();
  328. * $config_data = $config->get('bar');
  329. * @endcode
  330. * In this example $config_data would return an array with one key - 'baz' -
  331. * because 'boo' was unset.
  332. *
  333. * @section sec_entity Configuration entities
  334. * In contrast to the simple configuration settings described in the previous
  335. * section, if your module allows users to create zero or more items (where
  336. * "items" are things like content type definitions, view definitions, and the
  337. * like), then you need to define a configuration entity type to store your
  338. * configuration. Creating an entity type, loading entities, and querying them
  339. * are outlined in the @link entity_api Entity API topic. @endlink Here are a
  340. * few additional steps and notes specific to configuration entities:
  341. * - For examples, look for classes that implement
  342. * \Drupal\Core\Config\Entity\ConfigEntityInterface -- one good example is
  343. * the \Drupal\user\Entity\Role entity type.
  344. * - In the entity type annotation, you will need to define a 'config_prefix'
  345. * string. When Drupal stores a configuration item, it will be given a name
  346. * composed of your module name, your chosen config prefix, and the ID of
  347. * the individual item, separated by '.'. For example, in the Role entity,
  348. * the config prefix is 'role', so one configuration item might be named
  349. * user.role.anonymous, with configuration file user.role.anonymous.yml.
  350. * - You will need to define the schema for your configuration in your
  351. * modulename.schema.yml file, with an entry for 'modulename.config_prefix.*'.
  352. * For example, for the Role entity, the file user.schema.yml has an entry
  353. * user.role.*; see @ref sec_yaml above for more information.
  354. * - Your module can provide default/optional configuration entities in YAML
  355. * files; see @ref sec_yaml above for more information.
  356. * - Some configuration entities have dependencies on other configuration
  357. * entities, and module developers need to consider this so that configuration
  358. * can be imported, uninstalled, and synchronized in the right order. For
  359. * example, a field display configuration entity would need to depend on
  360. * field configuration, which depends on field and bundle configuration.
  361. * Configuration entity classes expose dependencies by overriding the
  362. * \Drupal\Core\Config\Entity\ConfigEntityInterface::calculateDependencies()
  363. * method.
  364. * - On routes for paths starting with '/admin' or otherwise designated as
  365. * administration paths (such as node editing when it is set as an admin
  366. * operation), if they have configuration entity placeholders, configuration
  367. * entities are normally loaded in their original language, without
  368. * translations or other overrides. This is usually desirable, because most
  369. * admin paths are for editing configuration, and you need that to be in the
  370. * source language and to lack possibly dynamic overrides. If for some reason
  371. * you need to have your configuration entity loaded in the currently-selected
  372. * language on an admin path (for instance, if you go to
  373. * example.com/es/admin/your_path and you need the entity to be in Spanish),
  374. * then you can add a 'with_config_overrides' parameter option to your route.
  375. * The same applies if you need to load the entity with overrides (or
  376. * translated) on an admin path like '/node/add/article' (when configured to
  377. * be an admin path). Here's an example using the configurable_language config
  378. * entity:
  379. * @code
  380. * mymodule.myroute:
  381. * path: '/admin/mypath/{configurable_language}'
  382. * defaults:
  383. * _controller: '\Drupal\mymodule\MyController::myMethod'
  384. * options:
  385. * parameters:
  386. * configurable_language:
  387. * type: entity:configurable_language
  388. * with_config_overrides: TRUE
  389. * @endcode
  390. * With the route defined this way, the $configurable_language parameter to
  391. * your controller method will come in translated to the current language.
  392. * Without the parameter options section, it would be in the original
  393. * language, untranslated.
  394. *
  395. * @see i18n
  396. *
  397. * @}
  398. */
  399. /**
  400. * @defgroup cache Cache API
  401. * @{
  402. * Information about the Drupal Cache API
  403. *
  404. * @section basics Basics
  405. *
  406. * Note: If not specified, all of the methods mentioned here belong to
  407. * \Drupal\Core\Cache\CacheBackendInterface.
  408. *
  409. * The Cache API is used to store data that takes a long time to compute.
  410. * Caching can either be permanent or valid only for a certain time span, and
  411. * the cache can contain any type of data.
  412. *
  413. * To use the Cache API:
  414. * - Request a cache object through \Drupal::cache() or by injecting a cache
  415. * service.
  416. * - Define a Cache ID (cid) value for your data. A cid is a string, which must
  417. * contain enough information to uniquely identify the data. For example, if
  418. * your data contains translated strings, then your cid value must include the
  419. * interface text language selected for page.
  420. * - Call the get() method to attempt a cache read, to see if the cache already
  421. * contains your data.
  422. * - If your data is not already in the cache, compute it and add it to the
  423. * cache using the set() method. The third argument of set() can be used to
  424. * control the lifetime of your cache item.
  425. *
  426. * Example:
  427. * @code
  428. * $cid = 'mymodule_example:' . \Drupal::languageManager()->getCurrentLanguage()->getId();
  429. *
  430. * $data = NULL;
  431. * if ($cache = \Drupal::cache()->get($cid)) {
  432. * $data = $cache->data;
  433. * }
  434. * else {
  435. * $data = my_module_complicated_calculation();
  436. * \Drupal::cache()->set($cid, $data);
  437. * }
  438. * @endcode
  439. *
  440. * Note the use of $data and $cache->data in the above example. Calls to
  441. * \Drupal::cache()->get() return a record that contains the information stored
  442. * by \Drupal::cache()->set() in the data property as well as additional meta
  443. * information about the cached data. In order to make use of the cached data
  444. * you can access it via $cache->data.
  445. *
  446. * @section bins Cache bins
  447. *
  448. * Cache storage is separated into "bins", each containing various cache items.
  449. * Each bin can be configured separately; see @ref configuration.
  450. *
  451. * When you request a cache object, you can specify the bin name in your call to
  452. * \Drupal::cache(). Alternatively, you can request a bin by getting service
  453. * "cache.nameofbin" from the container. The default bin is called "default", with
  454. * service name "cache.default", it is used to store common and frequently used
  455. * caches.
  456. *
  457. * Other common cache bins are the following:
  458. * - bootstrap: Data needed from the beginning to the end of most requests,
  459. * that has a very strict limit on variations and is invalidated rarely.
  460. * - render: Contains cached HTML strings like cached pages and blocks, can
  461. * grow to large size.
  462. * - data: Contains data that can vary by path or similar context.
  463. * - discovery: Contains cached discovery data for things such as plugins,
  464. * views_data, or YAML discovered data such as library info.
  465. *
  466. * A module can define a cache bin by defining a service in its
  467. * modulename.services.yml file as follows (substituting the desired name for
  468. * "nameofbin"):
  469. * @code
  470. * cache.nameofbin:
  471. * class: Drupal\Core\Cache\CacheBackendInterface
  472. * tags:
  473. * - { name: cache.bin }
  474. * factory: cache_factory:get
  475. * arguments: [nameofbin]
  476. * @endcode
  477. * See the @link container Services topic @endlink for more on defining
  478. * services.
  479. *
  480. * @section delete Deletion
  481. *
  482. * There are two ways to remove an item from the cache:
  483. * - Deletion (using delete(), deleteMultiple() or deleteAll()) permanently
  484. * removes the item from the cache.
  485. * - Invalidation (using invalidate(), invalidateMultiple() or invalidateAll())
  486. * is a "soft" delete that only marks items as "invalid", meaning "not fresh"
  487. * or "not fresh enough". Invalid items are not usually returned from the
  488. * cache, so in most ways they behave as if they have been deleted. However,
  489. * it is possible to retrieve invalid items, if they have not yet been
  490. * permanently removed by the garbage collector, by passing TRUE as the second
  491. * argument for get($cid, $allow_invalid).
  492. *
  493. * Use deletion if a cache item is no longer useful; for instance, if the item
  494. * contains references to data that has been deleted. Use invalidation if the
  495. * cached item may still be useful to some callers until it has been updated
  496. * with fresh data. The fact that it was fresh a short while ago may often be
  497. * sufficient.
  498. *
  499. * Invalidation is particularly useful to protect against stampedes. Rather than
  500. * having multiple concurrent requests updating the same cache item when it
  501. * expires or is deleted, there can be one request updating the cache, while the
  502. * other requests can proceed using the stale value. As soon as the cache item
  503. * has been updated, all future requests will use the updated value.
  504. *
  505. * @section tags Cache Tags
  506. *
  507. * The fourth argument of the set() method can be used to specify cache tags,
  508. * which are used to identify which data is included in each cache item. A cache
  509. * item can have multiple cache tags (an array of cache tags), and each cache
  510. * tag is a string. The convention is to generate cache tags of the form
  511. * [prefix]:[suffix]. Usually, you'll want to associate the cache tags of
  512. * entities, or entity listings. You won't have to manually construct cache tags
  513. * for them — just get their cache tags via
  514. * \Drupal\Core\Cache\CacheableDependencyInterface::getCacheTags() and
  515. * \Drupal\Core\Entity\EntityTypeInterface::getListCacheTags().
  516. * Data that has been tagged can be invalidated as a group: no matter the Cache
  517. * ID (cid) of the cache item, no matter in which cache bin a cache item lives;
  518. * as long as it is tagged with a certain cache tag, it will be invalidated.
  519. *
  520. * Because of that, cache tags are a solution to the cache invalidation problem:
  521. * - For caching to be effective, each cache item must only be invalidated when
  522. * absolutely necessary. (i.e. maximizing the cache hit ratio.)
  523. * - For caching to be correct, each cache item that depends on a certain thing
  524. * must be invalidated whenever that certain thing is modified.
  525. *
  526. * A typical scenario: a user has modified a node that appears in two views,
  527. * three blocks and on twelve pages. Without cache tags, we couldn't possibly
  528. * know which cache items to invalidate, so we'd have to invalidate everything:
  529. * we had to sacrifice effectiveness to achieve correctness. With cache tags, we
  530. * can have both.
  531. *
  532. * Example:
  533. * @code
  534. * // A cache item with nodes, users, and some custom module data.
  535. * $tags = array(
  536. * 'my_custom_tag',
  537. * 'node:1',
  538. * 'node:3',
  539. * 'user:7',
  540. * );
  541. * \Drupal::cache()->set($cid, $data, CacheBackendInterface::CACHE_PERMANENT, $tags);
  542. *
  543. * // Invalidate all cache items with certain tags.
  544. * \Drupal\Core\Cache\Cache::invalidateTags(array('user:1'));
  545. * @endcode
  546. *
  547. * Drupal is a content management system, so naturally you want changes to your
  548. * content to be reflected everywhere, immediately. That's why we made sure that
  549. * every entity type in Drupal 8 automatically has support for cache tags: when
  550. * you save an entity, you can be sure that the cache items that have the
  551. * corresponding cache tags will be invalidated.
  552. * This also is the case when you define your own entity types: you'll get the
  553. * exact same cache tag invalidation as any of the built-in entity types, with
  554. * the ability to override any of the default behavior if needed.
  555. * See \Drupal\Core\Cache\CacheableDependencyInterface::getCacheTags(),
  556. * \Drupal\Core\Entity\EntityTypeInterface::getListCacheTags(),
  557. * \Drupal\Core\Entity\Entity::invalidateTagsOnSave() and
  558. * \Drupal\Core\Entity\Entity::invalidateTagsOnDelete().
  559. *
  560. * @section context Cache contexts
  561. *
  562. * Some computed data depends on contextual data, such as the user roles of the
  563. * logged-in user who is viewing a page, the language the page is being rendered
  564. * in, the theme being used, etc. When caching the output of such a calculation,
  565. * you must cache each variation separately, along with information about which
  566. * variation of the contextual data was used in the calculation. The next time
  567. * the computed data is needed, if the context matches that for an existing
  568. * cached data set, the cached data can be reused; if no context matches, a new
  569. * data set can be calculated and cached for later use.
  570. *
  571. * Cache contexts are services tagged with 'cache.context', whose classes
  572. * implement \Drupal\Core\Cache\Context\CacheContextInterface. See
  573. * https://www.drupal.org/developing/api/8/cache/contexts for more information
  574. * on cache contexts, including a list of the contexts that exist in Drupal
  575. * core, and information on how to define your own contexts. See the
  576. * @link container Services and the Dependency Injection Container @endlink
  577. * topic for more information about services.
  578. *
  579. * Typically, the cache context is specified as part of the #cache property
  580. * of a render array; see the Caching section of the
  581. * @link theme_render Render API overview topic @endlink for details.
  582. *
  583. * @section configuration Configuration
  584. *
  585. * By default cached data is stored in the database. This can be configured
  586. * though so that all cached data, or that of an individual cache bin, uses a
  587. * different cache backend, such as APCu or Memcache, for storage.
  588. *
  589. * In a settings.php file, you can override the service used for a particular
  590. * cache bin. For example, if your service implementation of
  591. * \Drupal\Core\Cache\CacheBackendInterface was called cache.custom, the
  592. * following line would make Drupal use it for the 'cache_render' bin:
  593. * @code
  594. * $settings['cache']['bins']['render'] = 'cache.custom';
  595. * @endcode
  596. *
  597. * Additionally, you can register your cache implementation to be used by
  598. * default for all cache bins with:
  599. * @code
  600. * $settings['cache']['default'] = 'cache.custom';
  601. * @endcode
  602. *
  603. * For cache bins that are stored in the database, the number of rows is limited
  604. * to 5000 by default. This can be changed for all database cache bins. For
  605. * example, to instead limit the number of rows to 50000:
  606. * @code
  607. * $settings['database_cache_max_rows']['default'] = 50000;
  608. * @endcode
  609. *
  610. * Or per bin (in this example we allow infinite entries):
  611. * @code
  612. * $settings['database_cache_max_rows']['bins']['dynamic_page_cache'] = -1;
  613. * @endcode
  614. *
  615. * For monitoring reasons it might be useful to figure out the amount of data
  616. * stored in tables. The following SQL snippet can be used for that:
  617. * @code
  618. * SELECT table_name AS `Table`, table_rows AS 'Num. of Rows',
  619. * ROUND(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` FROM
  620. * information_schema.TABLES WHERE table_schema = '***DATABASE_NAME***' AND
  621. * table_name LIKE 'cache_%' ORDER BY (data_length + index_length) DESC
  622. * LIMIT 10;
  623. * @endcode
  624. *
  625. * @see \Drupal\Core\Cache\DatabaseBackend
  626. *
  627. * Finally, you can chain multiple cache backends together, see
  628. * \Drupal\Core\Cache\ChainedFastBackend and \Drupal\Core\Cache\BackendChain.
  629. *
  630. * @see https://www.drupal.org/node/1884796
  631. * @}
  632. */
  633. /**
  634. * @defgroup user_api User accounts, permissions, and roles
  635. * @{
  636. * API for user accounts, access checking, roles, and permissions.
  637. *
  638. * @section sec_overview Overview and terminology
  639. * Drupal's permission system is based on the concepts of accounts, roles,
  640. * and permissions.
  641. *
  642. * Users (site visitors) have accounts, which include a user name, an email
  643. * address, a password (or some other means of authentication), and possibly
  644. * other fields (if defined on the site). Anonymous users have an implicit
  645. * account that does not have a real user name or any account information.
  646. *
  647. * Each user account is assigned one or more roles. The anonymous user account
  648. * automatically has the anonymous user role; real user accounts
  649. * automatically have the authenticated user role, plus any roles defined on
  650. * the site that they have been assigned.
  651. *
  652. * Each role, including the special anonymous and authenticated user roles, is
  653. * granted one or more named permissions, which allow them to perform certain
  654. * tasks or view certain content on the site. It is possible to designate a
  655. * role to be the "administrator" role; if this is set up, this role is
  656. * automatically granted all available permissions whenever a module is
  657. * enabled that defines permissions.
  658. *
  659. * All code in Drupal that allows users to perform tasks or view content must
  660. * check that the current user has the correct permission before allowing the
  661. * action. In the standard case, access checking consists of answering the
  662. * question "Does the current user have permission 'foo'?", and allowing or
  663. * denying access based on the answer. Note that access checking should nearly
  664. * always be done at the permission level, not by checking for a particular role
  665. * or user ID, so that site administrators can set up user accounts and roles
  666. * appropriately for their particular sites.
  667. *
  668. * @section sec_define Defining permissions
  669. * Modules define permissions via a $module.permissions.yml file. See
  670. * \Drupal\user\PermissionHandler for documentation of permissions.yml files.
  671. *
  672. * @section sec_access Access permission checking
  673. * Depending on the situation, there are several methods for ensuring that
  674. * access checks are done properly in Drupal:
  675. * - Routes: When you register a route, include a 'requirements' section that
  676. * either gives the machine name of the permission that is needed to visit the
  677. * URL of the route, or tells Drupal to use an access check method or service
  678. * to check access. See the @link menu Routing topic @endlink for more
  679. * information.
  680. * - Entities: Access for various entity operations is designated either with
  681. * simple permissions or access control handler classes in the entity
  682. * annotation. See the @link entity_api Entity API topic @endlink for more
  683. * information.
  684. * - Other code: There is a 'current_user' service, which can be injected into
  685. * classes to provide access to the current user account (see the
  686. * @link container Services and Dependency Injection topic @endlink for more
  687. * information on dependency injection). In code that cannot use dependency
  688. * injection, you can access this service and retrieve the current user
  689. * account object by calling \Drupal::currentUser(). Once you have a user
  690. * object for the current user (implementing \Drupal\user\UserInterface), you
  691. * can call inherited method
  692. * \Drupal\Core\Session\AccountInterface::hasPermission() to check
  693. * permissions, or pass this object into other functions/methods.
  694. * - Forms: Each element of a form array can have a Boolean '#access' property,
  695. * which determines whether that element is visible and/or usable. This is a
  696. * common need in forms, so the current user service (described above) is
  697. * injected into the form base class as method
  698. * \Drupal\Core\Form\FormBase::currentUser().
  699. *
  700. * @section sec_entities User and role objects
  701. * User objects in Drupal are entity items, implementing
  702. * \Drupal\user\UserInterface. Role objects in Drupal are also entity items,
  703. * implementing \Drupal\user\RoleInterface. See the
  704. * @link entity_api Entity API topic @endlink for more information about
  705. * entities in general (including how to load, create, modify, and query them).
  706. *
  707. * Roles often need to be manipulated in automated test code, such as to add
  708. * permissions to them. Here's an example:
  709. * @code
  710. * $role = \Drupal\user\Entity\Role::load('authenticated');
  711. * $role->grantPermission('access comments');
  712. * $role->save();
  713. * @endcode
  714. *
  715. * Other important interfaces:
  716. * - \Drupal\Core\Session\AccountInterface: The part of UserInterface that
  717. * deals with access checking. In writing code that checks access, your
  718. * method parameters should use this interface, not UserInterface.
  719. * - \Drupal\Core\Session\AccountProxyInterface: The interface for the
  720. * current_user service (described above).
  721. * @}
  722. */
  723. /**
  724. * @defgroup container Services and Dependency Injection Container
  725. * @{
  726. * Overview of the Dependency Injection Container and Services.
  727. *
  728. * @section sec_overview Overview of container, injection, and services
  729. * The Services and Dependency Injection Container concepts have been adopted by
  730. * Drupal from the @link http://symfony.com/ Symfony framework. @endlink A
  731. * "service" (such as accessing the database, sending email, or translating user
  732. * interface text) is defined (given a name and an interface or at least a
  733. * class that defines the methods that may be called), and a default class is
  734. * designated to provide the service. These two steps must be done together, and
  735. * can be done by Drupal Core or a module. Other modules can then define
  736. * alternative classes to provide the same services, overriding the default
  737. * classes. Classes and functions that need to use the service should always
  738. * instantiate the class via the dependency injection container (also known
  739. * simply as the "container"), rather than instantiating a particular service
  740. * provider class directly, so that they get the correct class (default or
  741. * overridden).
  742. *
  743. * See https://www.drupal.org/node/2133171 for more detailed information on
  744. * services and the dependency injection container.
  745. *
  746. * @section sec_discover Discovering existing services
  747. * Drupal core defines many core services in the core.services.yml file (in the
  748. * top-level core directory). Some Drupal Core modules and contributed modules
  749. * also define services in modulename.services.yml files. API reference sites
  750. * (such as https://api.drupal.org) generate lists of all existing services from
  751. * these files. Look for the Services link in the API Navigation block.
  752. * Alternatively you can look through the individual files manually.
  753. *
  754. * A typical service definition in a *.services.yml file looks like this:
  755. * @code
  756. * path.alias_manager:
  757. * class: Drupal\Core\Path\AliasManager
  758. * arguments: ['@path.crud', '@path.alias_whitelist', '@language_manager']
  759. * @endcode
  760. * Some services use other services as factories; a typical service definition
  761. * is:
  762. * @code
  763. * cache.entity:
  764. * class: Drupal\Core\Cache\CacheBackendInterface
  765. * tags:
  766. * - { name: cache.bin }
  767. * factory: cache_factory:get
  768. * arguments: [entity]
  769. * @endcode
  770. *
  771. * The first line of a service definition gives the unique machine name of the
  772. * service. This is often prefixed by the module name if provided by a module;
  773. * however, by convention some service names are prefixed by a group name
  774. * instead, such as cache.* for cache bins and plugin.manager.* for plugin
  775. * managers.
  776. *
  777. * The class line either gives the default class that provides the service, or
  778. * if the service uses a factory class, the interface for the service. If the
  779. * class depends on other services, the arguments line lists the machine
  780. * names of the dependencies (preceded by '@'); objects for each of these
  781. * services are instantiated from the container and passed to the class
  782. * constructor when the service class is instantiated. Other arguments can also
  783. * be passed in; see the section at https://www.drupal.org/node/2133171 for more
  784. * detailed information.
  785. *
  786. * Services using factories can be defined as shown in the above example, if the
  787. * factory is itself a service. The factory can also be a class; details of how
  788. * to use service factories can be found in the section at
  789. * https://www.drupal.org/node/2133171.
  790. *
  791. * @section sec_container Accessing a service through the container
  792. * As noted above, if you need to use a service in your code, you should always
  793. * instantiate the service class via a call to the container, using the machine
  794. * name of the service, so that the default class can be overridden. There are
  795. * several ways to make sure this happens:
  796. * - For service-providing classes, see other sections of this documentation
  797. * describing how to pass services as arguments to the constructor.
  798. * - Plugin classes, controllers, and similar classes have create() or
  799. * createInstance() methods that are used to create an instance of the class.
  800. * These methods come from different interfaces, and have different
  801. * arguments, but they all include an argument $container of type
  802. * \Symfony\Component\DependencyInjection\ContainerInterface.
  803. * If you are defining one of these classes, in the create() or
  804. * createInstance() method, call $container->get('myservice.name') to
  805. * instantiate a service. The results of these calls are generally passed to
  806. * the class constructor and saved as member variables in the class.
  807. * - For functions and class methods that do not have access to either of
  808. * the above methods of dependency injection, you can use service location to
  809. * access services, via a call to the global \Drupal class. This class has
  810. * special methods for accessing commonly-used services, or you can call a
  811. * generic method to access any service. Examples:
  812. * @code
  813. * // Retrieve the entity.manager service object (special method exists).
  814. * $manager = \Drupal::entityManager();
  815. * // Retrieve the service object for machine name 'foo.bar'.
  816. * $foobar = \Drupal::service('foo.bar');
  817. * @endcode
  818. *
  819. * As a note, you should always use dependency injection (via service arguments
  820. * or create()/createInstance() methods) if possible to instantiate services,
  821. * rather than service location (via the \Drupal class), because:
  822. * - Dependency injection facilitates writing unit tests, since the container
  823. * argument can be mocked and the create() method can be bypassed by using
  824. * the class constructor. If you use the \Drupal class, unit tests are much
  825. * harder to write and your code has more dependencies.
  826. * - Having the service interfaces on the class constructor and member variables
  827. * is useful for IDE auto-complete and self-documentation.
  828. *
  829. * @section sec_define Defining a service
  830. * If your module needs to define a new service, here are the steps:
  831. * - Choose a unique machine name for your service. Typically, this should
  832. * start with your module name. Example: mymodule.myservice.
  833. * - Create a PHP interface to define what your service does.
  834. * - Create a default class implementing your interface that provides your
  835. * service. If your class needs to use existing services (such as database
  836. * access), be sure to make these services arguments to your class
  837. * constructor, and save them in member variables. Also, if the needed
  838. * services are provided by other modules and not Drupal Core, you'll want
  839. * these modules to be dependencies of your module.
  840. * - Add an entry to a modulename.services.yml file for the service. See
  841. * @ref sec_discover above, or existing *.services.yml files in Core, for the
  842. * syntax; it will start with your machine name, refer to your default class,
  843. * and list the services that need to be passed into your constructor.
  844. *
  845. * Services can also be defined dynamically, as in the
  846. * \Drupal\Core\CoreServiceProvider class, but this is less common for modules.
  847. *
  848. * @section sec_tags Service tags
  849. * Some services have tags, which are defined in the service definition. See
  850. * @link service_tag Service Tags @endlink for usage.
  851. *
  852. * @section sec_injection Overriding the default service class
  853. * Modules can override the default classes used for services. Here are the
  854. * steps:
  855. * - Define a class in the top-level namespace for your module
  856. * (Drupal\my_module), whose name is the camel-case version of your module's
  857. * machine name followed by "ServiceProvider" (for example, if your module
  858. * machine name is my_module, the class must be named
  859. * MyModuleServiceProvider).
  860. * - The class needs to implement
  861. * \Drupal\Core\DependencyInjection\ServiceModifierInterface, which is
  862. * typically done by extending
  863. * \Drupal\Core\DependencyInjection\ServiceProviderBase.
  864. * - The class needs to contain one method: alter(). This method does the
  865. * actual work of telling Drupal to use your class instead of the default.
  866. * Here's an example:
  867. * @code
  868. * public function alter(ContainerBuilder $container) {
  869. * // Override the language_manager class with a new class.
  870. * $definition = $container->getDefinition('language_manager');
  871. * $definition->setClass('Drupal\my_module\MyLanguageManager');
  872. * }
  873. * @endcode
  874. * Note that $container here is an instance of
  875. * \Drupal\Core\DependencyInjection\ContainerBuilder.
  876. *
  877. * @see https://www.drupal.org/node/2133171
  878. * @see core.services.yml
  879. * @see \Drupal
  880. * @see \Symfony\Component\DependencyInjection\ContainerInterface
  881. * @see plugin_api
  882. * @see menu
  883. * @}
  884. */
  885. /**
  886. * @defgroup listing_page_service Page header for Services page
  887. * @{
  888. * Introduction to services
  889. *
  890. * A "service" (such as accessing the database, sending email, or translating
  891. * user interface text) can be defined by a module or Drupal core. Defining a
  892. * service means giving it a name and designating a default class to provide the
  893. * service; ideally, there should also be an interface that defines the methods
  894. * that may be called. Services are collected into the Dependency Injection
  895. * Container, and can be overridden to use different classes or different
  896. * instantiation by modules. See the
  897. * @link container Services and Dependency Injection Container topic @endlink
  898. * for details.
  899. *
  900. * Some services have tags, which are defined in the service definition. Tags
  901. * are used to define a group of related services, or to specify some aspect of
  902. * how the service behaves. See the
  903. * @link service_tag Service Tags topic @endlink for more information.
  904. *
  905. * @see container
  906. * @see service_tag
  907. *
  908. * @}
  909. */
  910. /**
  911. * @defgroup typed_data Typed Data API
  912. * @{
  913. * API for describing data based on a set of available data types.
  914. *
  915. * PHP has data types, such as int, string, float, array, etc., and it is an
  916. * object-oriented language that lets you define classes and interfaces.
  917. * However, in some cases, it is useful to be able to define an abstract
  918. * type (as in an interface, free of implementation details), that still has
  919. * properties (which an interface cannot) as well as meta-data. The Typed Data
  920. * API provides this abstraction.
  921. *
  922. * @section sec_overview Overview
  923. * Each data type in the Typed Data API is a plugin class (annotation class
  924. * example: \Drupal\Core\TypedData\Annotation\DataType); these plugins are
  925. * managed by the typed_data_manager service (by default
  926. * \Drupal\Core\TypedData\TypedDataManager). Each data object encapsulates a
  927. * single piece of data, provides access to the metadata, and provides
  928. * validation capability. Also, the typed data plugins have a shorthand
  929. * for easily accessing data values, described in @ref sec_tree.
  930. *
  931. * The metadata of a data object is defined by an object based on a class called
  932. * the definition class (see \Drupal\Core\TypedData\DataDefinitionInterface).
  933. * The class used can vary by data type and can be specified in the data type's
  934. * plugin definition, while the default is set in the $definition_class property
  935. * of the annotation class. The default class is
  936. * \Drupal\Core\TypedData\DataDefinition. For data types provided by a plugin
  937. * deriver, the plugin deriver can set the definition_class property too.
  938. * The metadata object provides information about the data, such as the data
  939. * type, whether it is translatable, the names of its properties (for complex
  940. * types), and who can access it.
  941. *
  942. * See https://www.drupal.org/node/1794140 for more information about the Typed
  943. * Data API.
  944. *
  945. * @section sec_varieties Varieties of typed data
  946. * There are three kinds of typed data: primitive, complex, and list.
  947. *
  948. * @subsection sub_primitive Primitive data types
  949. * Primitive data types wrap PHP data types and also serve as building blocks
  950. * for complex and list typed data. Each primitive data type has an interface
  951. * that extends \Drupal\Core\TypedData\PrimitiveInterface, with getValue()
  952. * and setValue() methods for accessing the data value, and a default plugin
  953. * implementation. Here's a list:
  954. * - \Drupal\Core\TypedData\Type\IntegerInterface: Plugin ID integer,
  955. * corresponds to PHP type int.
  956. * - \Drupal\Core\TypedData\Type\StringInterface: Plugin ID string,
  957. * corresponds to PHP type string.
  958. * - \Drupal\Core\TypedData\Type\FloatInterface: Plugin ID float,
  959. * corresponds to PHP type float.
  960. * - \Drupal\Core\TypedData\Type\BooleanInterface: Plugin ID bool,
  961. * corresponds to PHP type bool.
  962. * - \Drupal\Core\TypedData\Type\BinaryInterface: Plugin ID binary,
  963. * corresponds to a PHP file resource.
  964. * - \Drupal\Core\TypedData\Type\UriInterface: Plugin ID uri.
  965. *
  966. * @subsection sec_complex Complex data
  967. * Complex data types, with interface
  968. * \Drupal\Core\TypedData\ComplexDataInterface, represent data with named
  969. * properties; the properties can be accessed with get() and set() methods.
  970. * The value of each property is itself a typed data object, which can be
  971. * primitive, complex, or list data.
  972. *
  973. * The base type for most complex data is the
  974. * \Drupal\Core\TypedData\Plugin\DataType\Map class, which represents an
  975. * associative array. Map provides its own definition class in the annotation,
  976. * \Drupal\Core\TypedData\MapDataDefinition, and most complex data classes
  977. * extend this class. The getValue() and setValue() methods on the Map class
  978. * enforce the data definition and its property structure.
  979. *
  980. * The Drupal Field API uses complex typed data for its field items, with
  981. * definition class \Drupal\Core\Field\TypedData\FieldItemDataDefinition.
  982. *
  983. * @section sec_list Lists
  984. * List data types, with interface \Drupal\Core\TypedData\ListInterface,
  985. * represent data that is an ordered list of typed data, all of the same type.
  986. * More precisely, the plugins in the list must have the same base plugin ID;
  987. * however, some types (for example field items and entities) are provided by
  988. * plugin derivatives and the sub IDs can be different.
  989. *
  990. * @section sec_tree Tree handling
  991. * Typed data allows you to use shorthand to get data values nested in the
  992. * implicit tree structure of the data. For example, to get the value from
  993. * an entity field item, the Entity Field API allows you to call:
  994. * @code
  995. * $value = $entity->fieldName->propertyName;
  996. * @endcode
  997. * This is really shorthand for:
  998. * @code
  999. * $field_item_list = $entity->get('fieldName');
  1000. * $field_item = $field_item_list->get(0);
  1001. * $property = $field_item->get('propertyName');
  1002. * $value = $property->getValue();
  1003. * @endcode
  1004. * Some notes:
  1005. * - $property, $field_item, and $field_item_list are all typed data objects,
  1006. * while $value is a raw PHP value.
  1007. * - You can call $property->getParent() to get $field_item,
  1008. * $field_item->getParent() to get $field_item_list, or
  1009. * $field_item_list->getParent() to get $typed_entity ($entity wrapped in a
  1010. * typed data object). $typed_entity->getParent() is NULL.
  1011. * - For all of these ->getRoot() returns $typed_entity.
  1012. * - The langcode property is on $field_item_list, but you can access it
  1013. * on $property as well, so that all items will report the same langcode.
  1014. * - When the value of $property is changed by calling $property->setValue(),
  1015. * $property->onChange() will fire, which in turn calls the parent object's
  1016. * onChange() method and so on. This allows parent objects to react upon
  1017. * changes of contained properties or list items.
  1018. *
  1019. * @section sec_defining Defining data types
  1020. * To define a new data type:
  1021. * - Create a class that implements one of the Typed Data interfaces.
  1022. * Typically, you will want to extend one of the classes listed in the
  1023. * sections above as a starting point.
  1024. * - Make your class into a DataType plugin. To do that, put it in namespace
  1025. * \Drupal\yourmodule\Plugin\DataType (where "yourmodule" is your module's
  1026. * short name), and add annotation of type
  1027. * \Drupal\Core\TypedData\Annotation\DataType to the documentation header.
  1028. * See the @link plugin_api Plugin API topic @endlink and the
  1029. * @link annotation Annotations topic @endlink for more information.
  1030. *
  1031. * @section sec_using Using data types
  1032. * The data types of the Typed Data API can be used in several ways, once they
  1033. * have been defined:
  1034. * - In the Field API, data types can be used as the class in the property
  1035. * definition of the field. See the @link field Field API topic @endlink for
  1036. * more information.
  1037. * - In configuration schema files, you can use the unique ID ('id' annotation)
  1038. * from any DataType plugin class as the 'type' value for an entry. See the
  1039. * @link config_api Confuration API topic @endlink for more information.
  1040. * - If you need to create a typed data object in code, first get the
  1041. * typed_data_manager service from the container or by calling
  1042. * \Drupal::typedDataManager(). Then pass the plugin ID to
  1043. * $manager::createDataDefinition() to create an appropriate data definition
  1044. * object. Then pass the data definition object and the value of the data to
  1045. * $manager::create() to create a typed data object.
  1046. *
  1047. * @see plugin_api
  1048. * @see container
  1049. * @}
  1050. */
  1051. /**
  1052. * @defgroup testing Automated tests
  1053. * @{
  1054. * Overview of PHPUnit tests and Simpletest tests.
  1055. *
  1056. * The Drupal project has embraced a philosophy of using automated tests,
  1057. * consisting of both unit tests (which test the functionality of classes at a
  1058. * low level) and functional tests (which test the functionality of Drupal
  1059. * systems at a higher level, usually involving web output). The goal is to
  1060. * have test coverage for all or most of the components and features, and to
  1061. * run the automated tests before any code is changed or added, to make sure
  1062. * it doesn't break any existing functionality (regression testing).
  1063. *
  1064. * In order to implement this philosophy, developers need to do the following:
  1065. * - When making a patch to fix a bug, make sure that the bug fix patch includes
  1066. * a test that fails without the code change and passes with the code change.
  1067. * This helps reviewers understand what the bug is, demonstrates that the code
  1068. * actually fixes the bug, and ensures the bug will not reappear due to later
  1069. * code changes.
  1070. * - When making a patch to implement a new feature, include new unit and/or
  1071. * functional tests in the patch. This serves to both demonstrate that the
  1072. * code actually works, and ensure that later changes do not break the new
  1073. * functionality.
  1074. *
  1075. * @section write_unit Writing PHPUnit tests for classes
  1076. * PHPUnit tests for classes are written using the industry-standard PHPUnit
  1077. * framework. Use a PHPUnit test to test functionality of a class if the Drupal
  1078. * environment (database, settings, etc.) and web browser are not needed for the
  1079. * test, or if the Drupal environment can be replaced by a "mock" object. To
  1080. * write a PHPUnit test:
  1081. * - Define a class that extends \Drupal\Tests\UnitTestCase.
  1082. * - The class name needs to end in the word Test.
  1083. * - The namespace must be a subspace/subdirectory of \Drupal\yourmodule\Tests,
  1084. * where yourmodule is your module's machine name.
  1085. * - The test class file must be named and placed under the
  1086. * yourmodule/tests/src/Unit directory, according to the PSR-4 standard.
  1087. * - Your test class needs a phpDoc comment block with a description and
  1088. * a @group annotation, which gives information about the test.
  1089. * - Add test cases by adding method names that start with 'test' and have no
  1090. * arguments, for example testYourTestCase(). Each one should test a logical
  1091. * subset of the functionality.
  1092. * For more details, see:
  1093. * - https://www.drupal.org/phpunit for full documentation on how to write
  1094. * PHPUnit tests for Drupal.
  1095. * - http://phpunit.de for general information on the PHPUnit framework.
  1096. * - @link oo_conventions Object-oriented programming topic @endlink for more
  1097. * on PSR-4, namespaces, and where to place classes.
  1098. *
  1099. * @section write_functional Writing functional tests
  1100. * Functional tests are written using a Drupal-specific framework that is, for
  1101. * historical reasons, known as "Simpletest". Use a Simpletest test to test the
  1102. * functionality of sub-system of Drupal, if the functionality depends on the
  1103. * Drupal database and settings, or to test the web output of Drupal. To
  1104. * write a Simpletest test:
  1105. * - For functional tests of the web output of Drupal, define a class that
  1106. * extends \Drupal\simpletest\WebTestBase, which contains an internal web
  1107. * browser and defines many helpful test assertion methods that you can use
  1108. * in your tests. You can specify modules to be enabled by defining a
  1109. * $modules member variable -- keep in mind that by default, WebTestBase uses
  1110. * a "testing" install profile, with a minimal set of modules enabled.
  1111. * - For functional tests that do not test web output, define a class that
  1112. * extends \Drupal\KernelTests\KernelTestBase. This class is much faster
  1113. * than WebTestBase, because instead of making a full install of Drupal, it
  1114. * uses an in-memory pseudo-installation (similar to what the installer and
  1115. * update scripts use). To use this test class, you will need to create the
  1116. * database tables you need and install needed modules manually.
  1117. * - The namespace must be a subspace/subdirectory of \Drupal\yourmodule\Tests,
  1118. * where yourmodule is your module's machine name.
  1119. * - The test class file must be named and placed under the yourmodule/src/Tests
  1120. * directory, according to the PSR-4 standard.
  1121. * - Your test class needs a phpDoc comment block with a description and
  1122. * a @group annotation, which gives information about the test.
  1123. * - You may also override the default setUp() method, which can set be used to
  1124. * set up content types and similar procedures.
  1125. * - In some cases, you may need to write a test module to support your test;
  1126. * put such modules under the yourmodule/tests/modules directory.
  1127. * - Add test cases by adding method names that start with 'test' and have no
  1128. * arguments, for example testYourTestCase(). Each one should test a logical
  1129. * subset of the functionality. Each method runs in a new, isolated test
  1130. * environment, so it can only rely on the setUp() method, not what has
  1131. * been set up by other test methods.
  1132. * For more details, see:
  1133. * - https://www.drupal.org/simpletest for full documentation on how to write
  1134. * functional tests for Drupal.
  1135. * - @link oo_conventions Object-oriented programming topic @endlink for more
  1136. * on PSR-4, namespaces, and where to place classes.
  1137. *
  1138. * @section write_functional_phpunit Write functional PHP tests (phpunit)
  1139. * Functional tests extend the BrowserTestBase base class, and use PHPUnit as
  1140. * their underlying framework. They use a simulated browser, in which the test
  1141. * can click links, visit URLs, post to forms, etc. To write a functional test:
  1142. * - Extend \Drupal\Tests\BrowserTestBase.
  1143. * - Place the test in the yourmodule/tests/src/Functional/ directory and use
  1144. * the \Drupal\Tests\yourmodule\Functional namespace.
  1145. * - Add a @group annotation. For example, if the test is for a Drupal 6
  1146. * migration process, the group core uses is migrate_drupal_6. Use yourmodule
  1147. * as the group name if the test does not belong to another larger group.
  1148. * - You may also override the default setUp() method, which can be used to set
  1149. * up content types and similar procedures. Don't forget to call the parent
  1150. * method.
  1151. * - In some cases, you may need to write a test module to support your test;
  1152. * put such modules under the yourmodule/tests/modules directory.
  1153. * - Add test cases by adding method names that start with 'test' and have no
  1154. * arguments, for example testYourTestCase(). Each one should test a logical
  1155. * subset of the functionality. Each method runs in a new, isolated test
  1156. * environment, so it can only rely on the setUp() method, not what has
  1157. * been set up by other test methods.
  1158. * For more details, see:
  1159. * - https://www.drupal.org/docs/8/phpunit/phpunit-browser-test-tutorial for
  1160. * a full tutorial on how to write functional PHPUnit tests for Drupal.
  1161. * - https://www.drupal.org/phpunit for the full documentation on how to write
  1162. * PHPUnit tests for Drupal.
  1163. *
  1164. * @section write_jsfunctional_phpunit Write functional JavaScript tests (phpunit)
  1165. * To write a functional test that relies on JavaScript:
  1166. * - Extend \Drupal\FunctionalJavaScriptTests\JavascriptTestBase.
  1167. * - Place the test into the yourmodule/tests/src/FunctionalJavascript/
  1168. * directory and use the \Drupal\Tests\yourmodule\FunctionalJavascript
  1169. * namespace.
  1170. * - Add a @group annotation. Use yourmodule as the group name if the test does
  1171. * not belong to another larger group.
  1172. * - Set up PhantomJS; see http://phantomjs.org/download.html.
  1173. * - To run tests, see core/tests/README.md.
  1174. * - When clicking a link/button with Ajax behavior attached, keep in mind that
  1175. * the underlying browser might take time to deliver changes to the HTML. Use
  1176. * $this->assertSession()->assertWaitOnAjaxRequest() to wait for the Ajax
  1177. * request to finish.
  1178. * For more details, see:
  1179. * - https://www.drupal.org/docs/8/phpunit/phpunit-javascript-testing-tutorial
  1180. * for a full tutorial on how to write PHPUnit JavaScript tests for Drupal.
  1181. * - https://www.drupal.org/phpunit for the full documentation on how to write
  1182. * PHPUnit tests for Drupal.
  1183. *
  1184. * @section running Running tests
  1185. * You can run both Simpletest and PHPUnit tests by enabling the core Testing
  1186. * module (core/modules/simpletest). Once that module is enabled, tests can be
  1187. * run using the core/scripts/run-tests.sh script, using
  1188. * @link https://www.drupal.org/project/drush Drush @endlink, or from the
  1189. * Testing module user interface.
  1190. *
  1191. * PHPUnit tests can also be run from the command line, using the PHPUnit
  1192. * framework. See https://www.drupal.org/node/2116263 for more information.
  1193. * @}
  1194. */
  1195. /**
  1196. * @defgroup php_assert PHP Runtime Assert Statements
  1197. * @{
  1198. * Use of the assert() statement in Drupal.
  1199. *
  1200. * Unit tests also use the term "assertion" to refer to test conditions, so to
  1201. * avoid confusion the term "runtime assertion" will be used for the assert()
  1202. * statement throughout the documentation.
  1203. *
  1204. * A runtime assertion is a statement that is expected to always be true at
  1205. * the point in the code it appears at. They are tested using PHP's internal
  1206. * @link http://php.net/assert assert() @endlink statement. If an
  1207. * assertion is ever FALSE it indicates an error in the code or in module or
  1208. * theme configuration files. User-provided configuration files should be
  1209. * verified with standard control structures at all times, not just checked in
  1210. * development environments with assert() statements on.
  1211. *
  1212. * The Drupal project primarily uses runtime assertions to enforce the
  1213. * expectations of the API by failing when incorrect calls are made by code
  1214. * under development. While PHP type hinting does this for objects and arrays,
  1215. * runtime assertions do this for scalars (strings, integers, floats, etc.) and
  1216. * complex data structures such as cache and render arrays. They ensure that
  1217. * methods' return values are the documented data types. They also verify that
  1218. * objects have been properly configured and set up by the service container.
  1219. * They supplement unit tests by checking scenarios that do not have unit tests
  1220. * written for them.
  1221. *
  1222. * There are two php settings which affect runtime assertions. The first,
  1223. * assert.exception, should always be set to 1. The second is zend.assertions.
  1224. * Set this to -1 in production and 1 in development.
  1225. *
  1226. * See https://www.drupal.org/node/2492225 for more information on runtime
  1227. * assertions.
  1228. * @}
  1229. */
  1230. /**
  1231. * @defgroup info_types Information types
  1232. * @{
  1233. * Types of information in Drupal.
  1234. *
  1235. * Drupal has several distinct types of information, each with its own methods
  1236. * for storage and retrieval:
  1237. * - Content: Information meant to be displayed on your site: articles, basic
  1238. * pages, images, files, custom blocks, etc. Content is stored and accessed
  1239. * using @link entity_api Entities @endlink.
  1240. * - Session: Information about individual users' interactions with the site,
  1241. * such as whether they are logged in. This is really "state" information, but
  1242. * it is not stored the same way so it's a separate type here. Session data is
  1243. * accessed via \Symfony\Component\HttpFoundation\Request::getSession(), which
  1244. * returns an instance of
  1245. * \Symfony\Component\HttpFoundation\Session\SessionInterface.
  1246. * See the @link session Sessions topic @endlink for more information.
  1247. * - State: Information of a temporary nature, generally machine-generated and
  1248. * not human-edited, about the current state of your site. Examples: the time
  1249. * when Cron was last run, whether node access permissions need rebuilding,
  1250. * etc. See @link state_api the State API topic @endlink for more information.
  1251. * - Configuration: Information about your site that is generally (or at least
  1252. * can be) human-edited, but is not Content, and is meant to be relatively
  1253. * permanent. Examples: the name of your site, the content types and views
  1254. * you have defined, etc. See
  1255. * @link config_api the Configuration API topic @endlink for more information.
  1256. *
  1257. * @see cache
  1258. * @see i18n
  1259. * @}
  1260. */
  1261. /**
  1262. * @defgroup extending Extending and altering Drupal
  1263. * @{
  1264. * Overview of extensions and alteration methods for Drupal.
  1265. *
  1266. * @section sec_types Types of extensions
  1267. * Drupal's core behavior can be extended and altered via these three basic
  1268. * types of extensions:
  1269. * - Themes: Themes alter the appearance of Drupal sites. They can include
  1270. * template files, which alter the HTML markup and other raw output of the
  1271. * site; CSS files, which alter the styling applied to the HTML; and
  1272. * JavaScript, Flash, images, and other files. For more information, see the
  1273. * @link theme_render Theme system and render API topic @endlink and
  1274. * https://www.drupal.org/docs/8/theming
  1275. * - Modules: Modules add to or alter the behavior and functionality of Drupal,
  1276. * by using one or more of the methods listed below. For more information
  1277. * about creating modules, see https://www.drupal.org/developing/modules/8
  1278. * - Installation profiles: Installation profiles can be used to
  1279. * create distributions, which are complete specific-purpose packages of
  1280. * Drupal including additional modules, themes, and data. For more
  1281. * information, see https://www.drupal.org/developing/distributions.
  1282. *
  1283. * @section sec_alter Alteration methods for modules
  1284. * Here is a list of the ways that modules can alter or extend Drupal's core
  1285. * behavior, or the behavior of other modules:
  1286. * - Hooks: Specially-named functions that a module defines, which are
  1287. * discovered and called at specific times, usually to alter behavior or data.
  1288. * See the @link hooks Hooks topic @endlink for more information.
  1289. * - Plugins: Classes that a module defines, which are discovered and
  1290. * instantiated at specific times to add functionality. See the
  1291. * @link plugin_api Plugin API topic @endlink for more information.
  1292. * - Entities: Special plugins that define entity types for storing new types
  1293. * of content or configuration in Drupal. See the
  1294. * @link entity_api Entity API topic @endlink for more information.
  1295. * - Services: Classes that perform basic operations within Drupal, such as
  1296. * accessing the database and sending email. See the
  1297. * @link container Dependency Injection Container and Services topic @endlink
  1298. * for more information.
  1299. * - Routing: Providing or altering "routes", which are URLs that Drupal
  1300. * responds to, or altering routing behavior with event listener classes.
  1301. * See the @link menu Routing and menu topic @endlink for more information.
  1302. * - Events: Modules can register as event subscribers; when an event is
  1303. * dispatched, a method is called on each registered subscriber, allowing each
  1304. * one to react. See the @link events Events topic @endlink for more
  1305. * information.
  1306. *
  1307. * @section sec_sample *.info.yml files
  1308. * Extensions must each be located in a directory whose name matches the short
  1309. * name (or machine name) of the extension, and this directory must contain a
  1310. * file named machine_name.info.yml (where machine_name is the machine name of
  1311. * the extension). See \Drupal\Core\Extension\InfoParserInterface::parse() for
  1312. * documentation of the format of .info.yml files.
  1313. * @}
  1314. */
  1315. /**
  1316. * @defgroup plugin_api Plugin API
  1317. * @{
  1318. * Using the Plugin API
  1319. *
  1320. * @section sec_overview Overview and terminology
  1321. *
  1322. * The basic idea of plugins is to allow a particular module or subsystem of
  1323. * Drupal to provide functionality in an extensible, object-oriented way. The
  1324. * controlling module or subsystem defines the basic framework (interface) for
  1325. * the functionality, and other modules can create plugins (implementing the
  1326. * interface) with particular behaviors. The controlling module instantiates
  1327. * existing plugins as needed, and calls methods to invoke their functionality.
  1328. * Examples of functionality in Drupal Core that use plugins include: the block
  1329. * system (block types are plugins), the entity/field system (entity types,
  1330. * field types, field formatters, and field widgets are plugins), the image
  1331. * manipulation system (image effects and image toolkits are plugins), and the
  1332. * search system (search page types are plugins).
  1333. *
  1334. * Plugins are grouped into plugin types, each generally defined by an
  1335. * interface. Each plugin type is managed by a plugin manager service, which
  1336. * uses a plugin discovery method to discover provided plugins of that type and
  1337. * instantiate them using a plugin factory.
  1338. *
  1339. * Some plugin types make use of the following concepts or components:
  1340. * - Plugin derivatives: Allows a single plugin class to present itself as
  1341. * multiple plugins. Example: the Menu module provides a block for each
  1342. * defined menu via a block plugin derivative.
  1343. * - Plugin mapping: Allows a plugin class to map a configuration string to an
  1344. * instance, and have the plugin automatically instantiated without writing
  1345. * additional code.
  1346. * - Plugin collections: Provide a way to lazily instantiate a set of plugin
  1347. * instances from a single plugin definition.
  1348. *
  1349. * There are several things a module developer may need to do with plugins:
  1350. * - Define a completely new plugin type: see @ref sec_define below.
  1351. * - Create a plugin of an existing plugin type: see @ref sec_create below.
  1352. * - Perform tasks that involve plugins: see @ref sec_use below.
  1353. *
  1354. * See https://www.drupal.org/developing/api/8/plugins for more detailed
  1355. * documentation on the plugin system. There are also topics for a few
  1356. * of the many existing types of plugins:
  1357. * - @link block_api Block API @endlink
  1358. * - @link entity_api Entity API @endlink
  1359. * - @link field Various types of field-related plugins @endlink
  1360. * - @link views_plugins Views plugins @endlink (has links to topics covering
  1361. * various specific types of Views plugins).
  1362. * - @link search Search page plugins @endlink
  1363. *
  1364. * @section sec_define Defining a new plugin type
  1365. * To define a new plugin type:
  1366. * - Define an interface for the plugin. This describes the common set of
  1367. * behavior, and the methods you will call on each plugin class that is
  1368. * instantiated. Usually this interface will extend one or more of the
  1369. * following interfaces:
  1370. * - \Drupal\Component\Plugin\PluginInspectionInterface
  1371. * - \Drupal\Component\Plugin\ConfigurablePluginInterface
  1372. * - \Drupal\Component\Plugin\ContextAwarePluginInterface
  1373. * - \Drupal\Core\Plugin\PluginFormInterface
  1374. * - \Drupal\Core\Executable\ExecutableInterface
  1375. * - (optional) Create a base class that provides a partial implementation of
  1376. * the interface, for the convenience of developers wishing to create plugins
  1377. * of your type. The base class usually extends
  1378. * \Drupal\Core\Plugin\PluginBase, or one of the base classes that extends
  1379. * this class.
  1380. * - Choose a method for plugin discovery, and define classes as necessary.
  1381. * See @ref sub_discovery below.
  1382. * - Create a plugin manager/factory class and service, which will discover and
  1383. * instantiate plugins. See @ref sub_manager below.
  1384. * - Use the plugin manager to instantiate plugins. Call methods on your plugin
  1385. * interface to perform the tasks of your plugin type.
  1386. * - (optional) If appropriate, define a plugin collection. See @ref
  1387. * sub_collection below for more information.
  1388. *
  1389. * @subsection sub_discovery Plugin discovery
  1390. * Plugin discovery is the process your plugin manager uses to discover the
  1391. * individual plugins of your type that have been defined by your module and
  1392. * other modules. Plugin discovery methods are classes that implement
  1393. * \Drupal\Component\Plugin\Discovery\DiscoveryInterface. Most plugin types use
  1394. * one of the following discovery mechanisms:
  1395. * - Annotation: Plugin classes are annotated and placed in a defined namespace
  1396. * subdirectory. Most Drupal Core plugins use this method of discovery.
  1397. * - Hook: Plugin modules need to implement a hook to tell the manager about
  1398. * their plugins.
  1399. * - YAML: Plugins are listed in YAML files. Drupal Core uses this method for
  1400. * discovering local tasks and local actions. This is mainly useful if all
  1401. * plugins use the same class, so it is kind of like a global derivative.
  1402. * - Static: Plugin classes are registered within the plugin manager class
  1403. * itself. Static discovery is only useful if modules cannot define new
  1404. * plugins of this type (if the list of available plugins is static).
  1405. *
  1406. * It is also possible to define your own custom discovery mechanism or mix
  1407. * methods together. And there are many more details, such as annotation
  1408. * decorators, that apply to some of the discovery methods. See
  1409. * https://www.drupal.org/developing/api/8/plugins for more details.
  1410. *
  1411. * The remainder of this documentation will assume Annotation-based discovery,
  1412. * since this is the most common method.
  1413. *
  1414. * @subsection sub_manager Defining a plugin manager class and service
  1415. * To define an annotation-based plugin manager:
  1416. * - Choose a namespace subdirectory for your plugin. For example, search page
  1417. * plugins go in directory Plugin/Search under the module namespace.
  1418. * - Define an annotation class for your plugin type. This class should extend
  1419. * \Drupal\Component\Annotation\Plugin, and for most plugin types, it should
  1420. * contain member variables corresponding to the annotations plugins will
  1421. * need to provide. All plugins have at least $id: a unique string
  1422. * identifier.
  1423. * - Define an alter hook for altering the discovered plugin definitions. You
  1424. * should document the hook in a *.api.php file.
  1425. * - Define a plugin manager class. This class should implement
  1426. * \Drupal\Component\Plugin\PluginManagerInterface; most plugin managers do
  1427. * this by extending \Drupal\Core\Plugin\DefaultPluginManager. If you do
  1428. * extend the default plugin manager, the only method you will probably need
  1429. * to define is the class constructor, which will need to call the parent
  1430. * constructor to provide information about the annotation class and plugin
  1431. * namespace for discovery, set up the alter hook, and possibly set up
  1432. * caching. See classes that extend DefaultPluginManager for examples.
  1433. * - Define a service for your plugin manager. See the
  1434. * @link container Services topic for more information. @endlink Your service
  1435. * definition should look something like this, referencing your manager
  1436. * class and the parent (default) plugin manager service to inherit
  1437. * constructor arguments:
  1438. * @code
  1439. * plugin.manager.mymodule:
  1440. * class: Drupal\mymodule\MyPluginManager
  1441. * parent: default_plugin_manager
  1442. * @endcode
  1443. * - If your plugin is configurable, you will also need to define the
  1444. * configuration schema and possibly a configuration entity type. See the
  1445. * @link config_api Configuration API topic @endlink for more information.
  1446. *
  1447. * @subsection sub_collection Defining a plugin collection
  1448. * Some configurable plugin types allow administrators to create zero or more
  1449. * instances of each plugin, each with its own configuration. For example,
  1450. * a single block plugin can be configured several times, to display in
  1451. * different regions of a theme, with different visibility settings, a
  1452. * different title, or other plugin-specific settings. To make this possible,
  1453. * a plugin type can make use of what's known as a plugin collection.
  1454. *
  1455. * A plugin collection is a class that extends
  1456. * \Drupal\Component\Plugin\LazyPluginCollection or one of its subclasses; there
  1457. * are several examples in Drupal Core. If your plugin type uses a plugin
  1458. * collection, it will usually also have a configuration entity, and the entity
  1459. * class should implement
  1460. * \Drupal\Core\Entity\EntityWithPluginCollectionInterface. Again, there are
  1461. * several examples in Drupal Core; see also the @link config_api Configuration
  1462. * API topic @endlink for more information about configuration entities.
  1463. *
  1464. * @section sec_create Creating a plugin of an existing type
  1465. * Assuming the plugin type uses annotation-based discovery, in order to create
  1466. * a plugin of an existing type, you will be creating a class. This class must:
  1467. * - Implement the plugin interface, so that it has the required methods
  1468. * defined. Usually, you'll want to extend the plugin base class, if one has
  1469. * been provided.
  1470. * - Have the right annotation in its documentation header. See the
  1471. * @link annotation Annotation topic @endlink for more information about
  1472. * annotation.
  1473. * - Be in the right plugin namespace, in order to be discovered.
  1474. * Often, the easiest way to make sure this happens is to find an existing
  1475. * example of a working plugin class of the desired type, and copy it into your
  1476. * module as a starting point.
  1477. *
  1478. * You can also create a plugin derivative, which allows your plugin class
  1479. * to present itself to the user interface as multiple plugins. To do this,
  1480. * in addition to the plugin class, you'll need to create a separate plugin
  1481. * derivative class implementing
  1482. * \Drupal\Component\Plugin\Derivative\DerivativeInterface. The classes
  1483. * \Drupal\system\Plugin\Block\SystemMenuBlock (plugin class) and
  1484. * \Drupal\system\Plugin\Derivative\SystemMenuBlock (derivative class) are a
  1485. * good example to look at.
  1486. *
  1487. * @section sec_use Performing tasks involving plugins
  1488. * Here are the steps to follow to perform a task that involves plugins:
  1489. * - Locate the machine name of the plugin manager service, and instantiate the
  1490. * service. See the @link container Services topic @endlink for more
  1491. * information on how to do this.
  1492. * - On the plugin manager class, use methods like getDefinition(),
  1493. * getDefinitions(), or other methods specific to particular plugin managers
  1494. * to retrieve information about either specific plugins or the entire list of
  1495. * defined plugins.
  1496. * - Call the createInstance() method on the plugin manager to instantiate
  1497. * individual plugin objects.
  1498. * - Call methods on the plugin objects to perform the desired tasks.
  1499. *
  1500. * @see annotation
  1501. * @}
  1502. */
  1503. /**
  1504. * @defgroup oo_conventions Objected-oriented programming conventions
  1505. * @{
  1506. * PSR-4, namespaces, class naming, and other conventions.
  1507. *
  1508. * A lot of the PHP code in Drupal is object oriented (OO), making use of
  1509. * @link http://php.net/manual/language.oop5.php PHP classes, interfaces, and traits @endlink
  1510. * (which are loosely referred to as "classes" in the rest of this topic). The
  1511. * following conventions and standards apply to this version of Drupal:
  1512. * - Each class must be in its own file.
  1513. * - Classes must be namespaced. If a module defines a class, the namespace
  1514. * must start with \Drupal\module_name. If it is defined by Drupal Core for
  1515. * use across many modules, the namespace should be \Drupal\Core or
  1516. * \Drupal\Component, with the exception of the global class \Drupal. See
  1517. * https://www.drupal.org/node/1353118 for more about namespaces.
  1518. * - In order for the PSR-4-based class auto-loader to find the class, it must
  1519. * be located in a directory corresponding to the namespace. For
  1520. * module-defined classes, if the namespace is \Drupal\module_name\foo\bar,
  1521. * then the class goes under the main module directory in directory
  1522. * src/foo/bar. For Drupal-wide classes, if the namespace is
  1523. * \Drupal\Core\foo\bar, then it goes in directory
  1524. * core/lib/Drupal/Core/foo/bar. See https://www.drupal.org/node/2156625 for
  1525. * more information about PSR-4.
  1526. * - Some classes have annotations added to their documentation headers. See
  1527. * the @link annotation Annotation topic @endlink for more information.
  1528. * - Standard plugin discovery requires particular namespaces and annotation
  1529. * for most plugin classes. See the
  1530. * @link plugin_api Plugin API topic @endlink for more information.
  1531. * - There are project-wide coding standards for OO code, including naming:
  1532. * https://www.drupal.org/node/608152
  1533. * - Documentation standards for classes are covered on:
  1534. * https://www.drupal.org/coding-standards/docs#classes
  1535. * @}
  1536. */
  1537. /**
  1538. * @defgroup listing_page_class Page header for Classes page
  1539. * @{
  1540. * Introduction to classes
  1541. *
  1542. * A lot of the PHP code in Drupal is object oriented (OO), making use of
  1543. * @link http://php.net/manual/language.oop5.php PHP classes, interfaces, and traits. @endlink
  1544. * See the
  1545. * @link oo_conventions Objected-oriented programming conventions @endlink
  1546. * for more information.
  1547. *
  1548. * @see oo_conventions
  1549. *
  1550. * @}
  1551. */
  1552. /**
  1553. * @defgroup listing_page_namespace Page header for Namespaces page
  1554. * @{
  1555. * Introduction to namespaces
  1556. *
  1557. * PHP classes, interfaces, and traits in Drupal are
  1558. * @link http://php.net/manual/language.namespaces.rationale.php namespaced. @endlink
  1559. * See the
  1560. * @link oo_conventions Objected-oriented programming conventions @endlink
  1561. * for more information.
  1562. *
  1563. * @see oo_conventions
  1564. *
  1565. * @}
  1566. */
  1567. /**
  1568. * @defgroup best_practices Best practices for developers
  1569. * @{
  1570. * Overview of standards and best practices for developers
  1571. *
  1572. * Ideally, all code that is included in Drupal Core and contributed modules,
  1573. * themes, and distributions will be secure, internationalized, maintainable,
  1574. * and efficient. In order to facilitate this, the Drupal community has
  1575. * developed a set of guidelines and standards for developers to follow. Most of
  1576. * these standards can be found under
  1577. * @link https://www.drupal.org/developing/best-practices Best practices on Drupal.org @endlink
  1578. *
  1579. * Standards and best practices that developers should be aware of include:
  1580. * - Security: https://www.drupal.org/writing-secure-code and the
  1581. * @link sanitization Sanitization functions topic @endlink
  1582. * - Coding standards: https://www.drupal.org/coding-standards
  1583. * and https://www.drupal.org/coding-standards/docs
  1584. * - Accessibility: https://www.drupal.org/node/1637990 (modules) and
  1585. * https://www.drupal.org/node/464472 (themes)
  1586. * - Usability: https://www.drupal.org/ui-standards
  1587. * - Internationalization: @link i18n Internationalization topic @endlink
  1588. * - Automated testing: @link testing Automated tests topic @endlink
  1589. * @}
  1590. */
  1591. /**
  1592. * @defgroup utility Utility classes and functions
  1593. * @{
  1594. * Overview of utility classes and functions for developers.
  1595. *
  1596. * Drupal provides developers with a variety of utility functions that make it
  1597. * easier and more efficient to perform tasks that are either really common,
  1598. * tedious, or difficult. Utility functions help to reduce code duplication and
  1599. * should be used in place of one-off code whenever possible.
  1600. *
  1601. * @see common.inc
  1602. * @see file
  1603. * @see format
  1604. * @see php_wrappers
  1605. * @see sanitization
  1606. * @see transliteration
  1607. * @see validation
  1608. * @}
  1609. */
  1610. /**
  1611. * @defgroup hooks Hooks
  1612. * @{
  1613. * Define functions that alter the behavior of Drupal core.
  1614. *
  1615. * One way for modules to alter the core behavior of Drupal (or another module)
  1616. * is to use hooks. Hooks are specially-named functions that a module defines
  1617. * (this is known as "implementing the hook"), which are discovered and called
  1618. * at specific times to alter or add to the base behavior or data (this is
  1619. * known as "invoking the hook"). Each hook has a name (example:
  1620. * hook_batch_alter()), a defined set of parameters, and a defined return value.
  1621. * Your modules can implement hooks that are defined by Drupal core or other
  1622. * modules that they interact with. Your modules can also define their own
  1623. * hooks, in order to let other modules interact with them.
  1624. *
  1625. * To implement a hook:
  1626. * - Locate the documentation for the hook. Hooks are documented in *.api.php
  1627. * files, by defining functions whose name starts with "hook_" (these
  1628. * files and their functions are never loaded by Drupal -- they exist solely
  1629. * for documentation). The function should have a documentation header, as
  1630. * well as a sample function body. For example, in the core file
  1631. * system.api.php, you can find hooks such as hook_batch_alter(). Also, if
  1632. * you are viewing this documentation on an API reference site, the Core
  1633. * hooks will be listed in this topic.
  1634. * - Copy the function to your module's .module file.
  1635. * - Change the name of the function, substituting your module's short name
  1636. * (name of the module's directory, and .info.yml file without the extension)
  1637. * for the "hook" part of the sample function name. For instance, to implement
  1638. * hook_batch_alter(), you would rename it to my_module_batch_alter().
  1639. * - Edit the documentation for the function (normally, your implementation
  1640. * should just have one line saying "Implements hook_batch_alter().").
  1641. * - Edit the body of the function, substituting in what you need your module
  1642. * to do.
  1643. *
  1644. * To define a hook:
  1645. * - Choose a unique name for your hook. It should start with "hook_", followed
  1646. * by your module's short name.
  1647. * - Provide documentation in a *.api.php file in your module's main
  1648. * directory. See the "implementing" section above for details of what this
  1649. * should contain (parameters, return value, and sample function body).
  1650. * - Invoke the hook in your module's code.
  1651. *
  1652. * To invoke a hook, use methods on
  1653. * \Drupal\Core\Extension\ModuleHandlerInterface such as alter(), invoke(),
  1654. * and invokeAll(). You can obtain a module handler by calling
  1655. * \Drupal::moduleHandler(), or getting the 'module_handler' service on an
  1656. * injected container.
  1657. *
  1658. * @see extending
  1659. * @see themeable
  1660. * @see callbacks
  1661. * @see \Drupal\Core\Extension\ModuleHandlerInterface
  1662. * @see \Drupal::moduleHandler()
  1663. *
  1664. * @}
  1665. */
  1666. /**
  1667. * @defgroup callbacks Callbacks
  1668. * @{
  1669. * Callback function signatures.
  1670. *
  1671. * Drupal's API sometimes uses callback functions to allow you to define how
  1672. * some type of processing happens. A callback is a function with a defined
  1673. * signature, which you define in a module. Then you pass the function name as
  1674. * a parameter to a Drupal API function or return it as part of a hook
  1675. * implementation return value, and your function is called at an appropriate
  1676. * time. For instance, when setting up batch processing you might need to
  1677. * provide a callback function for each processing step and/or a callback for
  1678. * when processing is finished; you would do that by defining these functions
  1679. * and passing their names into the batch setup function.
  1680. *
  1681. * Callback function signatures, like hook definitions, are described by
  1682. * creating and documenting dummy functions in a *.api.php file; normally, the
  1683. * dummy callback function's name should start with "callback_", and you should
  1684. * document the parameters and return value and provide a sample function body.
  1685. * Then your API documentation can refer to this callback function in its
  1686. * documentation. A user of your API can usually name their callback function
  1687. * anything they want, although a standard name would be to replace "callback_"
  1688. * with the module name.
  1689. *
  1690. * @see hooks
  1691. * @see themeable
  1692. *
  1693. * @}
  1694. */
  1695. /**
  1696. * @defgroup form_api Form generation
  1697. * @{
  1698. * Describes how to generate and manipulate forms and process form submissions.
  1699. *
  1700. * Drupal provides a Form API in order to achieve consistency in its form
  1701. * processing and presentation, while simplifying code and reducing the amount
  1702. * of HTML that must be explicitly generated by a module.
  1703. *
  1704. * @section generating_forms Creating forms
  1705. * Forms are defined as classes that implement the
  1706. * \Drupal\Core\Form\FormInterface and are built using the
  1707. * \Drupal\Core\Form\FormBuilder class. Drupal provides a couple of utility
  1708. * classes that can be extended as a starting point for most basic forms, the
  1709. * most commonly used of which is \Drupal\Core\Form\FormBase. FormBuilder
  1710. * handles the low level processing of forms such as rendering the necessary
  1711. * HTML, initial processing of incoming $_POST data, and delegating to your
  1712. * implementation of FormInterface for validation and processing of submitted
  1713. * data.
  1714. *
  1715. * Here is an example of a Form class:
  1716. * @code
  1717. * namespace Drupal\mymodule\Form;
  1718. *
  1719. * use Drupal\Core\Form\FormBase;
  1720. * use Drupal\Core\Form\FormStateInterface;
  1721. *
  1722. * class ExampleForm extends FormBase {
  1723. * public function getFormId() {
  1724. * // Unique ID of the form.
  1725. * return 'example_form';
  1726. * }
  1727. *
  1728. * public function buildForm(array $form, FormStateInterface $form_state) {
  1729. * // Create a $form API array.
  1730. * $form['phone_number'] = array(
  1731. * '#type' => 'tel',
  1732. * '#title' => $this->t('Your phone number'),
  1733. * );
  1734. * $form['save'] = array(
  1735. * '#type' => 'submit',
  1736. * '#value' => $this->t('Save'),
  1737. * );
  1738. * return $form;
  1739. * }
  1740. *
  1741. * public function validateForm(array &$form, FormStateInterface $form_state) {
  1742. * // Validate submitted form data.
  1743. * }
  1744. *
  1745. * public function submitForm(array &$form, FormStateInterface $form_state) {
  1746. * // Handle submitted form data.
  1747. * }
  1748. * }
  1749. * @endcode
  1750. *
  1751. * @section retrieving_forms Retrieving and displaying forms
  1752. * \Drupal::formBuilder()->getForm() should be used to handle retrieving,
  1753. * processing, and displaying a rendered HTML form. Given the ExampleForm
  1754. * defined above,
  1755. * \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm') would
  1756. * return the rendered HTML of the form defined by ExampleForm::buildForm(), or
  1757. * call the validateForm() and submitForm(), methods depending on the current
  1758. * processing state.
  1759. *
  1760. * The argument to \Drupal::formBuilder()->getForm() is the name of a class that
  1761. * implements FormInterface. Any additional arguments passed to the getForm()
  1762. * method will be passed along as additional arguments to the
  1763. * ExampleForm::buildForm() method.
  1764. *
  1765. * For example:
  1766. * @code
  1767. * $extra = '612-123-4567';
  1768. * $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm', $extra);
  1769. * ...
  1770. * public function buildForm(array $form, FormStateInterface $form_state, $extra = NULL)
  1771. * $form['phone_number'] = array(
  1772. * '#type' => 'tel',
  1773. * '#title' => $this->t('Your phone number'),
  1774. * '#value' => $extra,
  1775. * );
  1776. * return $form;
  1777. * }
  1778. * @endcode
  1779. *
  1780. * Alternatively, forms can be built directly via the routing system which will
  1781. * take care of calling \Drupal::formBuilder()->getForm(). The following example
  1782. * demonstrates the use of a routing.yml file to display a form at the given
  1783. * route.
  1784. *
  1785. * @code
  1786. * example.form:
  1787. * path: '/example-form'
  1788. * defaults:
  1789. * _title: 'Example form'
  1790. * _form: '\Drupal\mymodule\Form\ExampleForm'
  1791. * @endcode
  1792. *
  1793. * The $form argument to form-related functions is a specialized render array
  1794. * containing the elements and properties of the form. For more about render
  1795. * arrays, see the @link theme_render Render API topic. @endlink For more
  1796. * detailed explanations of the Form API workflow, see the
  1797. * @link https://www.drupal.org/node/2117411 Form API documentation section. @endlink
  1798. * In addition, there is a set of Form API tutorials in the
  1799. * @link https://www.drupal.org/project/examples Examples for Developers project. @endlink
  1800. *
  1801. * In the form builder, validation, submission, and other form methods,
  1802. * $form_state is the primary influence on the processing of the form and is
  1803. * passed to most methods, so they can use it to communicate with the form
  1804. * system and each other. $form_state is an object that implements
  1805. * \Drupal\Core\Form\FormStateInterface.
  1806. * @}
  1807. */
  1808. /**
  1809. * @defgroup queue Queue operations
  1810. * @{
  1811. * Queue items to allow later processing.
  1812. *
  1813. * The queue system allows placing items in a queue and processing them later.
  1814. * The system tries to ensure that only one consumer can process an item.
  1815. *
  1816. * Before a queue can be used it needs to be created by
  1817. * Drupal\Core\Queue\QueueInterface::createQueue().
  1818. *
  1819. * Items can be added to the queue by passing an arbitrary data object to
  1820. * Drupal\Core\Queue\QueueInterface::createItem().
  1821. *
  1822. * To process an item, call Drupal\Core\Queue\QueueInterface::claimItem() and
  1823. * specify how long you want to have a lease for working on that item.
  1824. * When finished processing, the item needs to be deleted by calling
  1825. * Drupal\Core\Queue\QueueInterface::deleteItem(). If the consumer dies, the
  1826. * item will be made available again by the Drupal\Core\Queue\QueueInterface
  1827. * implementation once the lease expires. Another consumer will then be able to
  1828. * receive it when calling Drupal\Core\Queue\QueueInterface::claimItem().
  1829. * Due to this, the processing code should be aware that an item might be handed
  1830. * over for processing more than once.
  1831. *
  1832. * The $item object used by the Drupal\Core\Queue\QueueInterface can contain
  1833. * arbitrary metadata depending on the implementation. Systems using the
  1834. * interface should only rely on the data property which will contain the
  1835. * information passed to Drupal\Core\Queue\QueueInterface::createItem().
  1836. * The full queue item returned by Drupal\Core\Queue\QueueInterface::claimItem()
  1837. * needs to be passed to Drupal\Core\Queue\QueueInterface::deleteItem() once
  1838. * processing is completed.
  1839. *
  1840. * There are two kinds of queue backends available: reliable, which preserves
  1841. * the order of messages and guarantees that every item will be executed at
  1842. * least once. The non-reliable kind only does a best effort to preserve order
  1843. * in messages and to execute them at least once but there is a small chance
  1844. * that some items get lost. For example, some distributed back-ends like
  1845. * Amazon SQS will be managing jobs for a large set of producers and consumers
  1846. * where a strict FIFO ordering will likely not be preserved. Another example
  1847. * would be an in-memory queue backend which might lose items if it crashes.
  1848. * However, such a backend would be able to deal with significantly more writes
  1849. * than a reliable queue and for many tasks this is more important. See
  1850. * aggregator_cron() for an example of how to effectively use a non-reliable
  1851. * queue. Another example is doing Twitter statistics -- the small possibility
  1852. * of losing a few items is insignificant next to power of the queue being able
  1853. * to keep up with writes. As described in the processing section, regardless
  1854. * of the queue being reliable or not, the processing code should be aware that
  1855. * an item might be handed over for processing more than once (because the
  1856. * processing code might time out before it finishes).
  1857. * @}
  1858. */
  1859. /**
  1860. * @defgroup annotation Annotations
  1861. * @{
  1862. * Annotations for class discovery and metadata description.
  1863. *
  1864. * The Drupal plugin system has a set of reusable components that developers
  1865. * can use, override, and extend in their modules. Most of the plugins use
  1866. * annotations, which let classes register themselves as plugins and describe
  1867. * their metadata. (Annotations can also be used for other purposes, though
  1868. * at the moment, Drupal only uses them for the plugin system.)
  1869. *
  1870. * To annotate a class as a plugin, add code similar to the following to the
  1871. * end of the documentation block immediately preceding the class declaration:
  1872. * @code
  1873. * * @ContentEntityType(
  1874. * * id = "comment",
  1875. * * label = @Translation("Comment"),
  1876. * * ...
  1877. * * base_table = "comment"
  1878. * * )
  1879. * @endcode
  1880. *
  1881. * Note that you must use double quotes; single quotes will not work in
  1882. * annotations.
  1883. *
  1884. * Some annotation types, which extend the "@ PluginID" annotation class, have
  1885. * only a single 'id' key in their annotation. For these, it is possible to use
  1886. * a shorthand annotation. For example:
  1887. * @code
  1888. * * @ViewsArea("entity")
  1889. * @endcode
  1890. * in place of
  1891. * @code
  1892. * * @ViewsArea(
  1893. * * id = "entity"
  1894. * *)
  1895. * @endcode
  1896. *
  1897. * The available annotation classes are listed in this topic, and can be
  1898. * identified when you are looking at the Drupal source code by having
  1899. * "@ Annotation" in their documentation blocks (without the space after @). To
  1900. * find examples of annotation for a particular annotation class, such as
  1901. * EntityType, look for class files that have an @ annotation section using the
  1902. * annotation class.
  1903. *
  1904. * @see plugin_translatable
  1905. * @see plugin_context
  1906. *
  1907. * @}
  1908. */
  1909. /**
  1910. * @addtogroup hooks
  1911. * @{
  1912. */
  1913. /**
  1914. * Perform periodic actions.
  1915. *
  1916. * Modules that require some commands to be executed periodically can
  1917. * implement hook_cron(). The engine will then call the hook whenever a cron
  1918. * run happens, as defined by the administrator. Typical tasks managed by
  1919. * hook_cron() are database maintenance, backups, recalculation of settings
  1920. * or parameters, automated mailing, and retrieving remote data.
  1921. *
  1922. * Short-running or non-resource-intensive tasks can be executed directly in
  1923. * the hook_cron() implementation.
  1924. *
  1925. * Long-running tasks and tasks that could time out, such as retrieving remote
  1926. * data, sending email, and intensive file tasks, should use the queue API
  1927. * instead of executing the tasks directly. To do this, first define one or
  1928. * more queues via a \Drupal\Core\Annotation\QueueWorker plugin. Then, add items
  1929. * that need to be processed to the defined queues.
  1930. */
  1931. function hook_cron() {
  1932. // Short-running operation example, not using a queue:
  1933. // Delete all expired records since the last cron run.
  1934. $expires = \Drupal::state()->get('mymodule.last_check', 0);
  1935. \Drupal::database()->delete('mymodule_table')
  1936. ->condition('expires', $expires, '>=')
  1937. ->execute();
  1938. \Drupal::state()->set('mymodule.last_check', REQUEST_TIME);
  1939. // Long-running operation example, leveraging a queue:
  1940. // Queue news feeds for updates once their refresh interval has elapsed.
  1941. $queue = \Drupal::queue('aggregator_feeds');
  1942. $ids = \Drupal::entityManager()->getStorage('aggregator_feed')->getFeedIdsToRefresh();
  1943. foreach (Feed::loadMultiple($ids) as $feed) {
  1944. if ($queue->createItem($feed)) {
  1945. // Add timestamp to avoid queueing item more than once.
  1946. $feed->setQueuedTime(REQUEST_TIME);
  1947. $feed->save();
  1948. }
  1949. }
  1950. $ids = \Drupal::entityQuery('aggregator_feed')
  1951. ->condition('queued', REQUEST_TIME - (3600 * 6), '<')
  1952. ->execute();
  1953. if ($ids) {
  1954. $feeds = Feed::loadMultiple($ids);
  1955. foreach ($feeds as $feed) {
  1956. $feed->setQueuedTime(0);
  1957. $feed->save();
  1958. }
  1959. }
  1960. }
  1961. /**
  1962. * Alter available data types for typed data wrappers.
  1963. *
  1964. * @param array $data_types
  1965. * An array of data type information.
  1966. *
  1967. * @see hook_data_type_info()
  1968. */
  1969. function hook_data_type_info_alter(&$data_types) {
  1970. $data_types['email']['class'] = '\Drupal\mymodule\Type\Email';
  1971. }
  1972. /**
  1973. * Alter cron queue information before cron runs.
  1974. *
  1975. * Called by \Drupal\Core\Cron to allow modules to alter cron queue settings
  1976. * before any jobs are processed.
  1977. *
  1978. * @param array $queues
  1979. * An array of cron queue information.
  1980. *
  1981. * @see \Drupal\Core\Queue\QueueWorkerInterface
  1982. * @see \Drupal\Core\Annotation\QueueWorker
  1983. * @see \Drupal\Core\Cron
  1984. */
  1985. function hook_queue_info_alter(&$queues) {
  1986. // This site has many feeds so let's spend 90 seconds on each cron run
  1987. // updating feeds instead of the default 60.
  1988. $queues['aggregator_feeds']['cron']['time'] = 90;
  1989. }
  1990. /**
  1991. * Alter an email message created with MailManagerInterface->mail().
  1992. *
  1993. * Hook hook_mail_alter() allows modification of email messages created and sent
  1994. * with MailManagerInterface->mail(). Usage examples include adding and/or
  1995. * changing message text, message fields, and message headers.
  1996. *
  1997. * Email messages sent using functions other than MailManagerInterface->mail()
  1998. * will not invoke hook_mail_alter(). For example, a contributed module directly
  1999. * calling the MailInterface->mail() or PHP mail() function will not invoke
  2000. * this hook. All core modules use MailManagerInterface->mail() for messaging,
  2001. * it is best practice but not mandatory in contributed modules.
  2002. *
  2003. * @param $message
  2004. * An array containing the message data. Keys in this array include:
  2005. * - 'id':
  2006. * The MailManagerInterface->mail() id of the message. Look at module source
  2007. * code or MailManagerInterface->mail() for possible id values.
  2008. * - 'to':
  2009. * The address or addresses the message will be sent to. The
  2010. * formatting of this string must comply with RFC 2822.
  2011. * - 'from':
  2012. * The address the message will be marked as being from, which is
  2013. * either a custom address or the site-wide default email address.
  2014. * - 'subject':
  2015. * Subject of the email to be sent. This must not contain any newline
  2016. * characters, or the email may not be sent properly.
  2017. * - 'body':
  2018. * An array of strings or objects that implement
  2019. * \Drupal\Component\Render\MarkupInterface containing the message text. The
  2020. * message body is created by concatenating the individual array strings
  2021. * into a single text string using "\n\n" as a separator.
  2022. * - 'headers':
  2023. * Associative array containing mail headers, such as From, Sender,
  2024. * MIME-Version, Content-Type, etc.
  2025. * - 'params':
  2026. * An array of optional parameters supplied by the caller of
  2027. * MailManagerInterface->mail() that is used to build the message before
  2028. * hook_mail_alter() is invoked.
  2029. * - 'language':
  2030. * The language object used to build the message before hook_mail_alter()
  2031. * is invoked.
  2032. * - 'send':
  2033. * Set to FALSE to abort sending this email message.
  2034. *
  2035. * @see \Drupal\Core\Mail\MailManagerInterface::mail()
  2036. */
  2037. function hook_mail_alter(&$message) {
  2038. if ($message['id'] == 'modulename_messagekey') {
  2039. if (!example_notifications_optin($message['to'], $message['id'])) {
  2040. // If the recipient has opted to not receive such messages, cancel
  2041. // sending.
  2042. $message['send'] = FALSE;
  2043. return;
  2044. }
  2045. $message['body'][] = "--\nMail sent out from " . \Drupal::config('system.site')->get('name');
  2046. }
  2047. }
  2048. /**
  2049. * Prepares a message based on parameters;
  2050. *
  2051. * This hook is called from MailManagerInterface->mail(). Note that hook_mail(),
  2052. * unlike hook_mail_alter(), is only called on the $module argument to
  2053. * MailManagerInterface->mail(), not all modules.
  2054. *
  2055. * @param $key
  2056. * An identifier of the mail.
  2057. * @param $message
  2058. * An array to be filled in. Elements in this array include:
  2059. * - id: An ID to identify the mail sent. Look at module source code or
  2060. * MailManagerInterface->mail() for possible id values.
  2061. * - to: The address or addresses the message will be sent to. The
  2062. * formatting of this string must comply with RFC 2822.
  2063. * - subject: Subject of the email to be sent. This must not contain any
  2064. * newline characters, or the mail may not be sent properly.
  2065. * MailManagerInterface->mail() sets this to an empty
  2066. * string when the hook is invoked.
  2067. * - body: An array of lines containing the message to be sent. Drupal will
  2068. * format the correct line endings for you. MailManagerInterface->mail()
  2069. * sets this to an empty array when the hook is invoked. The array may
  2070. * contain either strings or objects implementing
  2071. * \Drupal\Component\Render\MarkupInterface.
  2072. * - from: The address the message will be marked as being from, which is
  2073. * set by MailManagerInterface->mail() to either a custom address or the
  2074. * site-wide default email address when the hook is invoked.
  2075. * - headers: Associative array containing mail headers, such as From,
  2076. * Sender, MIME-Version, Content-Type, etc.
  2077. * MailManagerInterface->mail() pre-fills several headers in this array.
  2078. * @param $params
  2079. * An array of parameters supplied by the caller of
  2080. * MailManagerInterface->mail().
  2081. *
  2082. * @see \Drupal\Core\Mail\MailManagerInterface::mail()
  2083. */
  2084. function hook_mail($key, &$message, $params) {
  2085. $account = $params['account'];
  2086. $context = $params['context'];
  2087. $variables = [
  2088. '%site_name' => \Drupal::config('system.site')->get('name'),
  2089. '%username' => $account->getDisplayName(),
  2090. ];
  2091. if ($context['hook'] == 'taxonomy') {
  2092. $entity = $params['entity'];
  2093. $vocabulary = Vocabulary::load($entity->id());
  2094. $variables += [
  2095. '%term_name' => $entity->name,
  2096. '%term_description' => $entity->description,
  2097. '%term_id' => $entity->id(),
  2098. '%vocabulary_name' => $vocabulary->label(),
  2099. '%vocabulary_description' => $vocabulary->getDescription(),
  2100. '%vocabulary_id' => $vocabulary->id(),
  2101. ];
  2102. }
  2103. // Node-based variable translation is only available if we have a node.
  2104. if (isset($params['node'])) {
  2105. /** @var \Drupal\node\NodeInterface $node */
  2106. $node = $params['node'];
  2107. $variables += [
  2108. '%uid' => $node->getOwnerId(),
  2109. '%url' => $node->url('canonical', ['absolute' => TRUE]),
  2110. '%node_type' => node_get_type_label($node),
  2111. '%title' => $node->getTitle(),
  2112. '%teaser' => $node->teaser,
  2113. '%body' => $node->body,
  2114. ];
  2115. }
  2116. $subject = strtr($context['subject'], $variables);
  2117. $body = strtr($context['message'], $variables);
  2118. $message['subject'] .= str_replace(["\r", "\n"], '', $subject);
  2119. $message['body'][] = MailFormatHelper::htmlToText($body);
  2120. }
  2121. /**
  2122. * Alter the list of mail backend plugin definitions.
  2123. *
  2124. * @param array $info
  2125. * The mail backend plugin definitions to be altered.
  2126. *
  2127. * @see \Drupal\Core\Annotation\Mail
  2128. * @see \Drupal\Core\Mail\MailManager
  2129. */
  2130. function hook_mail_backend_info_alter(&$info) {
  2131. unset($info['test_mail_collector']);
  2132. }
  2133. /**
  2134. * Alter the default country list.
  2135. *
  2136. * @param $countries
  2137. * The associative array of countries keyed by two-letter country code.
  2138. *
  2139. * @see \Drupal\Core\Locale\CountryManager::getList()
  2140. */
  2141. function hook_countries_alter(&$countries) {
  2142. // Elbonia is now independent, so add it to the country list.
  2143. $countries['EB'] = 'Elbonia';
  2144. }
  2145. /**
  2146. * Alter display variant plugin definitions.
  2147. *
  2148. * @param array $definitions
  2149. * The array of display variant definitions, keyed by plugin ID.
  2150. *
  2151. * @see \Drupal\Core\Display\VariantManager
  2152. * @see \Drupal\Core\Display\Annotation\DisplayVariant
  2153. */
  2154. function hook_display_variant_plugin_alter(array &$definitions) {
  2155. $definitions['full_page']['admin_label'] = t('Block layout');
  2156. }
  2157. /**
  2158. * Allow modules to alter layout plugin definitions.
  2159. *
  2160. * @param \Drupal\Core\Layout\LayoutDefinition[] $definitions
  2161. * The array of layout definitions, keyed by plugin ID.
  2162. */
  2163. function hook_layout_alter(&$definitions) {
  2164. // Remove a layout.
  2165. unset($definitions['twocol']);
  2166. }
  2167. /**
  2168. * Flush all persistent and static caches.
  2169. *
  2170. * This hook asks your module to clear all of its static caches,
  2171. * in order to ensure a clean environment for subsequently
  2172. * invoked data rebuilds.
  2173. *
  2174. * Do NOT use this hook for rebuilding information. Only use it to flush custom
  2175. * caches.
  2176. *
  2177. * Static caches using drupal_static() do not need to be reset manually.
  2178. * However, all other static variables that do not use drupal_static() must be
  2179. * manually reset.
  2180. *
  2181. * This hook is invoked by drupal_flush_all_caches(). It runs before module data
  2182. * is updated and before hook_rebuild().
  2183. *
  2184. * @see drupal_flush_all_caches()
  2185. * @see hook_rebuild()
  2186. */
  2187. function hook_cache_flush() {
  2188. if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
  2189. _update_cache_clear();
  2190. }
  2191. }
  2192. /**
  2193. * Rebuild data based upon refreshed caches.
  2194. *
  2195. * This hook allows your module to rebuild its data based on the latest/current
  2196. * module data. It runs after hook_cache_flush() and after all module data has
  2197. * been updated.
  2198. *
  2199. * This hook is only invoked after the system has been completely cleared;
  2200. * i.e., all previously cached data is known to be gone and every API in the
  2201. * system is known to return current information, so your module can safely rely
  2202. * on all available data to rebuild its own.
  2203. *
  2204. * @see hook_cache_flush()
  2205. * @see drupal_flush_all_caches()
  2206. */
  2207. function hook_rebuild() {
  2208. $themes = \Drupal::service('theme_handler')->listInfo();
  2209. foreach ($themes as $theme) {
  2210. _block_rehash($theme->getName());
  2211. }
  2212. }
  2213. /**
  2214. * Alter the configuration synchronization steps.
  2215. *
  2216. * @param array $sync_steps
  2217. * A one-dimensional array of \Drupal\Core\Config\ConfigImporter method names
  2218. * or callables that are invoked to complete the import, in the order that
  2219. * they will be processed. Each callable item defined in $sync_steps should
  2220. * either be a global function or a public static method. The callable should
  2221. * accept a $context array by reference. For example:
  2222. * @code
  2223. * function _additional_configuration_step(&$context) {
  2224. * // Do stuff.
  2225. * // If finished set $context['finished'] = 1.
  2226. * }
  2227. * @endcode
  2228. * For more information on creating batches, see the
  2229. * @link batch Batch operations @endlink documentation.
  2230. *
  2231. * @see callback_batch_operation()
  2232. * @see \Drupal\Core\Config\ConfigImporter::initialize()
  2233. */
  2234. function hook_config_import_steps_alter(&$sync_steps, \Drupal\Core\Config\ConfigImporter $config_importer) {
  2235. $deletes = $config_importer->getUnprocessedConfiguration('delete');
  2236. if (isset($deletes['field.storage.node.body'])) {
  2237. $sync_steps[] = '_additional_configuration_step';
  2238. }
  2239. }
  2240. /**
  2241. * Alter config typed data definitions.
  2242. *
  2243. * For example you can alter the typed data types representing each
  2244. * configuration schema type to change default labels or form element renderers
  2245. * used for configuration translation.
  2246. *
  2247. * If implementations of this hook add or remove configuration schema a
  2248. * ConfigSchemaAlterException will be thrown. Keep in mind that there are tools
  2249. * that may use the configuration schema for static analysis of configuration
  2250. * files, like the string extractor for the localization system. Such systems
  2251. * won't work with dynamically defined configuration schemas.
  2252. *
  2253. * For adding new data types use configuration schema YAML files instead.
  2254. *
  2255. * @param $definitions
  2256. * Associative array of configuration type definitions keyed by schema type
  2257. * names. The elements are themselves array with information about the type.
  2258. *
  2259. * @see \Drupal\Core\Config\TypedConfigManager
  2260. * @see \Drupal\Core\Config\Schema\ConfigSchemaAlterException
  2261. */
  2262. function hook_config_schema_info_alter(&$definitions) {
  2263. // Enhance the text and date type definitions with classes to generate proper
  2264. // form elements in ConfigTranslationFormBase. Other translatable types will
  2265. // appear as a one line textfield.
  2266. $definitions['text']['form_element_class'] = '\Drupal\config_translation\FormElement\Textarea';
  2267. $definitions['date_format']['form_element_class'] = '\Drupal\config_translation\FormElement\DateFormat';
  2268. }
  2269. /**
  2270. * Alter validation constraint plugin definitions.
  2271. *
  2272. * @param array[] $definitions
  2273. * The array of validation constraint definitions, keyed by plugin ID.
  2274. *
  2275. * @see \Drupal\Core\Validation\ConstraintManager
  2276. * @see \Drupal\Core\Validation\Annotation\Constraint
  2277. */
  2278. function hook_validation_constraint_alter(array &$definitions) {
  2279. $definitions['Null']['class'] = '\Drupal\mymodule\Validator\Constraints\MyClass';
  2280. }
  2281. /**
  2282. * @} End of "addtogroup hooks".
  2283. */
  2284. /**
  2285. * @defgroup ajax Ajax API
  2286. * @{
  2287. * Overview for Drupal's Ajax API.
  2288. *
  2289. * @section sec_overview Overview of Ajax
  2290. * Ajax is the process of dynamically updating parts of a page's HTML based on
  2291. * data from the server. When a specified event takes place, a PHP callback is
  2292. * triggered, which performs server-side logic and may return updated markup or
  2293. * JavaScript commands to run. After the return, the browser runs the JavaScript
  2294. * or updates the markup on the fly, with no full page refresh necessary.
  2295. *
  2296. * Many different events can trigger Ajax responses, including:
  2297. * - Clicking a button
  2298. * - Pressing a key
  2299. * - Moving the mouse
  2300. *
  2301. * @section sec_framework Ajax responses in forms
  2302. * Forms that use the Drupal Form API (see the
  2303. * @link form_api Form API topic @endlink for more information about forms) can
  2304. * trigger AJAX responses. Here is an outline of the steps:
  2305. * - Add property '#ajax' to a form element in your form array, to trigger an
  2306. * Ajax response.
  2307. * - Write an Ajax callback to process the input and respond.
  2308. * See sections below for details on these two steps.
  2309. *
  2310. * @subsection sub_form Adding Ajax triggers to a form
  2311. * As an example of adding Ajax triggers to a form, consider editing a date
  2312. * format, where the user is provided with a sample of the generated date output
  2313. * as they type. To accomplish this, typing in the text field should trigger an
  2314. * Ajax response. This is done in the text field form array element
  2315. * in \Drupal\config_translation\FormElement\DateFormat::getFormElement():
  2316. * @code
  2317. * '#ajax' => array(
  2318. * 'callback' => 'Drupal\config_translation\FormElement\DateFormat::ajaxSample',
  2319. * 'event' => 'keyup',
  2320. * 'progress' => array(
  2321. * 'type' => 'throbber',
  2322. * 'message' => NULL,
  2323. * ),
  2324. * ),
  2325. * @endcode
  2326. *
  2327. * As you can see from this example, the #ajax property for a form element is
  2328. * an array. Here are the details of its elements, all of which are optional:
  2329. * - callback: The callback to invoke to handle the server side of the
  2330. * Ajax event. More information on callbacks is below in @ref sub_callback.
  2331. * - wrapper: The HTML 'id' attribute of the area where the content returned by
  2332. * the callback should be placed. Note that callbacks have a choice of
  2333. * returning content or JavaScript commands; 'wrapper' is used for content
  2334. * returns.
  2335. * - method: The jQuery method for placing the new content (used with
  2336. * 'wrapper'). Valid options are 'replaceWith' (default), 'append', 'prepend',
  2337. * 'before', 'after', or 'html'. See
  2338. * http://api.jquery.com/category/manipulation/ for more information on these
  2339. * methods.
  2340. * - effect: The jQuery effect to use when placing the new HTML (used with
  2341. * 'wrapper'). Valid options are 'none' (default), 'slide', or 'fade'.
  2342. * - speed: The effect speed to use (used with 'effect' and 'wrapper'). Valid
  2343. * options are 'slow' (default), 'fast', or the number of milliseconds the
  2344. * effect should run.
  2345. * - event: The JavaScript event to respond to. This is selected automatically
  2346. * for the type of form element; provide a value to override the default.
  2347. * - prevent: A JavaScript event to prevent when the event is triggered. For
  2348. * example, if you use event 'mousedown' on a button, you might want to
  2349. * prevent 'click' events from also being triggered.
  2350. * - progress: An array indicating how to show Ajax processing progress. Can
  2351. * contain one or more of these elements:
  2352. * - type: Type of indicator: 'throbber' (default) or 'bar'.
  2353. * - message: Translated message to display.
  2354. * - url: For a bar progress indicator, URL path for determining progress.
  2355. * - interval: For a bar progress indicator, how often to update it.
  2356. * - url: A \Drupal\Core\Url to which to submit the Ajax request. If omitted,
  2357. * defaults to either the same URL as the form or link destination is for
  2358. * someone with JavaScript disabled, or a slightly modified version (e.g.,
  2359. * with a query parameter added, removed, or changed) of that URL if
  2360. * necessary to support Drupal's content negotiation. It is recommended to
  2361. * omit this key and use Drupal's content negotiation rather than using
  2362. * substantially different URLs between Ajax and non-Ajax.
  2363. *
  2364. * @subsection sub_callback Setting up a callback to process Ajax
  2365. * Once you have set up your form to trigger an Ajax response (see @ref sub_form
  2366. * above), you need to write some PHP code to process the response. If you use
  2367. * 'path' in your Ajax set-up, your route controller will be triggered with only
  2368. * the information you provide in the URL. If you use 'callback', your callback
  2369. * method is a function, which will receive the $form and $form_state from the
  2370. * triggering form. You can use $form_state to get information about the
  2371. * data the user has entered into the form. For instance, in the above example
  2372. * for the date format preview,
  2373. * \Drupal\config_translation\FormElement\DateFormat\ajaxSample() does this to
  2374. * get the format string entered by the user:
  2375. * @code
  2376. * $format_value = \Drupal\Component\Utility\NestedArray::getValue(
  2377. * $form_state->getValues(),
  2378. * $form_state->getTriggeringElement()['#array_parents']);
  2379. * @endcode
  2380. *
  2381. * Once you have processed the input, you have your choice of returning HTML
  2382. * markup or a set of Ajax commands. If you choose to return HTML markup, you
  2383. * can return it as a string or a renderable array, and it will be placed in
  2384. * the defined 'wrapper' element (see documentation above in @ref sub_form).
  2385. * In addition, any messages returned by
  2386. * \Drupal\Core\Messenger\Messenger::all(), themed as in
  2387. * status-messages.html.twig, will be prepended.
  2388. *
  2389. * To return commands, you need to set up an object of class
  2390. * \Drupal\Core\Ajax\AjaxResponse, and then use its addCommand() method to add
  2391. * individual commands to it. In the date format preview example, the format
  2392. * output is calculated, and then it is returned as replacement markup for a div
  2393. * like this:
  2394. * @code
  2395. * $response = new AjaxResponse();
  2396. * $response->addCommand(new ReplaceCommand(
  2397. * '#edit-date-format-suffix',
  2398. * '<small id="edit-date-format-suffix">' . $format . '</small>'));
  2399. * return $response;
  2400. * @endcode
  2401. *
  2402. * The individual commands that you can return implement interface
  2403. * \Drupal\Core\Ajax\CommandInterface. Available commands provide the ability
  2404. * to pop up alerts, manipulate text and markup in various ways, redirect
  2405. * to a new URL, and the generic \Drupal\Core\Ajax\InvokeCommand, which
  2406. * invokes an arbitrary jQuery command.
  2407. *
  2408. * As noted above, status messages are prepended automatically if you use the
  2409. * 'wrapper' method and return HTML markup. This is not the case if you return
  2410. * commands, but if you would like to show status messages, you can add
  2411. * @code
  2412. * array('#type' => 'status_messages')
  2413. * @endcode
  2414. * to a render array, use drupal_render() to render it, and add a command to
  2415. * place the messages in an appropriate location.
  2416. *
  2417. * @section sec_other Other methods for triggering Ajax
  2418. * Here are some additional methods you can use to trigger Ajax responses in
  2419. * Drupal:
  2420. * - Add class 'use-ajax' to a link. The link will be loaded using an Ajax
  2421. * call. When using this method, the href of the link can contain '/nojs/' as
  2422. * part of the path. When the Ajax JavaScript processes the page, it will
  2423. * convert this to '/ajax/'. The server is then able to easily tell if this
  2424. * request was made through an actual Ajax request or in a degraded state, and
  2425. * respond appropriately.
  2426. * - Add class 'use-ajax-submit' to a submit button in a form. The form will
  2427. * then be submitted via Ajax to the path specified in the #action. Like the
  2428. * ajax-submit class on links, this path will have '/nojs/' replaced with
  2429. * '/ajax/' so that the submit handler can tell if the form was submitted in a
  2430. * degraded state or not.
  2431. * - Add property '#autocomplete_route_name' to a text field in a form. The
  2432. * route controller for this route must return an array of options for
  2433. * autocomplete, as a \Symfony\Component\HttpFoundation\JsonResponse object.
  2434. * See the @link menu Routing topic @endlink for more information about
  2435. * routing.
  2436. */
  2437. /**
  2438. * @} End of "defgroup ajax".
  2439. */
  2440. /**
  2441. * @defgroup service_tag Service Tags
  2442. * @{
  2443. * Service tags overview
  2444. *
  2445. * Some services have tags, which are defined in the service definition. Tags
  2446. * are used to define a group of related services, or to specify some aspect of
  2447. * how the service behaves. Typically, if you tag a service, your service class
  2448. * must also implement a corresponding interface. Some common examples:
  2449. * - access_check: Indicates a route access checking service; see the
  2450. * @link menu Menu and routing system topic @endlink for more information.
  2451. * - cache.bin: Indicates a cache bin service; see the
  2452. * @link cache Cache topic @endlink for more information.
  2453. * - event_subscriber: Indicates an event subscriber service. Event subscribers
  2454. * can be used for dynamic routing and route altering; see the
  2455. * @link menu Menu and routing system topic @endlink for more information.
  2456. * They can also be used for other purposes; see
  2457. * http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html
  2458. * for more information.
  2459. * - needs_destruction: Indicates that a destruct() method needs to be called
  2460. * at the end of a request to finalize operations, if this service was
  2461. * instantiated. Services should implement \Drupal\Core\DestructableInterface
  2462. * in this case.
  2463. * - context_provider: Indicates a block context provider, used for example
  2464. * by block conditions. It has to implement
  2465. * \Drupal\Core\Plugin\Context\ContextProviderInterface.
  2466. * - http_client_middleware: Indicates that the service provides a guzzle
  2467. * middleware, see
  2468. * https://guzzle.readthedocs.org/en/latest/handlers-and-middleware.html for
  2469. * more information.
  2470. *
  2471. * Creating a tag for a service does not do anything on its own, but tags
  2472. * can be discovered or queried in a compiler pass when the container is built,
  2473. * and a corresponding action can be taken. See
  2474. * \Drupal\Core\Render\MainContent\MainContentRenderersPass for an example of
  2475. * finding tagged services.
  2476. *
  2477. * See @link container Services and Dependency Injection Container @endlink for
  2478. * information on services and the dependency injection container.
  2479. *
  2480. * @}
  2481. */
  2482. /**
  2483. * @defgroup events Events
  2484. * @{
  2485. * Overview of event dispatch and subscribing
  2486. *
  2487. * @section sec_intro Introduction and terminology
  2488. * Events are part of the Symfony framework: they allow for different components
  2489. * of the system to interact and communicate with each other. Each event has a
  2490. * unique string name. One system component dispatches the event at an
  2491. * appropriate time; many events are dispatched by Drupal core and the Symfony
  2492. * framework in every request. Other system components can register as event
  2493. * subscribers; when an event is dispatched, a method is called on each
  2494. * registered subscriber, allowing each one to react. For more on the general
  2495. * concept of events, see
  2496. * http://symfony.com/doc/current/components/event_dispatcher/introduction.html
  2497. *
  2498. * @section sec_dispatch Dispatching events
  2499. * To dispatch an event, call the
  2500. * \Symfony\Component\EventDispatcher\EventDispatcherInterface::dispatch()
  2501. * method on the 'event_dispatcher' service (see the
  2502. * @link container Services topic @endlink for more information about how to
  2503. * interact with services). The first argument is the unique event name, which
  2504. * you should normally define as a constant in a separate static class (see
  2505. * \Symfony\Component\HttpKernel\KernelEvents and
  2506. * \Drupal\Core\Config\ConfigEvents for examples). The second argument is a
  2507. * \Symfony\Component\EventDispatcher\Event object; normally you will need to
  2508. * extend this class, so that your event class can provide data to the event
  2509. * subscribers.
  2510. *
  2511. * @section sec_subscribe Registering event subscribers
  2512. * Here are the steps to register an event subscriber:
  2513. * - Define a service in your module, tagged with 'event_subscriber' (see the
  2514. * @link container Services topic @endlink for instructions).
  2515. * - Define a class for your subscriber service that implements
  2516. * \Symfony\Component\EventDispatcher\EventSubscriberInterface
  2517. * - In your class, the getSubscribedEvents method returns a list of the events
  2518. * this class is subscribed to, and which methods on the class should be
  2519. * called for each one. Example:
  2520. * @code
  2521. * public static function getSubscribedEvents() {
  2522. * // Subscribe to kernel terminate with priority 100.
  2523. * $events[KernelEvents::TERMINATE][] = array('onTerminate', 100);
  2524. * // Subscribe to kernel request with default priority of 0.
  2525. * $events[KernelEvents::REQUEST][] = array('onRequest');
  2526. * return $events;
  2527. * }
  2528. * @endcode
  2529. * - Write the methods that respond to the events; each one receives the
  2530. * event object provided in the dispatch as its one argument. In the above
  2531. * example, you would need to write onTerminate() and onRequest() methods.
  2532. *
  2533. * Note that in your getSubscribedEvents() method, you can optionally set the
  2534. * priority of your event subscriber (see terminate example above). Event
  2535. * subscribers with higher priority numbers get executed first; the default
  2536. * priority is zero. If two event subscribers for the same event have the same
  2537. * priority, the one defined in a module with a lower module weight will fire
  2538. * first. Subscribers defined in the same services file are fired in
  2539. * definition order. If order matters defining a priority is strongly advised
  2540. * instead of relying on these two tie breaker rules as they might change in a
  2541. * minor release.
  2542. * @}
  2543. */
  2544. /**
  2545. * @defgroup session Sessions
  2546. * @{
  2547. * Store and retrieve data associated with a user's browsing session.
  2548. *
  2549. * @section sec_intro Overview
  2550. * The Drupal session management subsystem is built on top of the Symfony
  2551. * session component. It is optimized in order to minimize the impact of
  2552. * anonymous sessions on caching proxies. A session is only started if necessary
  2553. * and the session cookie is removed from the browser as soon as the session
  2554. * has no data. For this reason it is important for contributed and custom
  2555. * code to remove session data if it is not used anymore.
  2556. *
  2557. * @section sec_usage Usage
  2558. * Session data is accessed via the
  2559. * \Symfony\Component\HttpFoundation\Request::getSession()
  2560. * method, which returns an instance of
  2561. * \Symfony\Component\HttpFoundation\Session\SessionInterface. The most
  2562. * important methods on SessionInterface are set(), get(), and remove().
  2563. *
  2564. * The following code fragment shows the implementation of a counter controller
  2565. * relying on the session:
  2566. * @code
  2567. * public function counter(Request $request) {
  2568. * $session = $request->getSession();
  2569. * $count = $session->get('mymodule.counter', 0) + 1;
  2570. * $session->set('mymodule.counter', $count);
  2571. *
  2572. * return [
  2573. * '#markup' => $this->t('Page Views: @count', ['@count' => $count]),
  2574. * '#cache' => [
  2575. * 'max-age' => 0,
  2576. * ],
  2577. * ];
  2578. * }
  2579. *
  2580. * public function reset(Request $request) {
  2581. * $session = $request->getSession();
  2582. * $session->remove('mymodule.counter');
  2583. * }
  2584. * @endcode
  2585. *
  2586. * It is important to keep the amount of data stored inside the session to a
  2587. * minimum, as the complete session is loaded on every request. Also third
  2588. * party session storage backends do not necessarily allow objects of unlimited
  2589. * size. If it is necessary to collect a non-trivial amount of data specific to
  2590. * a user's session, use the Key/Value store to save the serialized data and
  2591. * only store the key to the entry in the session.
  2592. *
  2593. * @section sec_reserved Reserved attributes and namespacing
  2594. * Contributed modules relying on the session are encouraged to namespace
  2595. * session attributes by prefixing them with their project name or an
  2596. * abbreviation thereof.
  2597. *
  2598. * Some attributes are reserved for Drupal core and must not be accessed from
  2599. * within contributed and custom code. Reserved attributes include:
  2600. * - uid: The user ID for an authenticated user. The value of this attribute
  2601. * cannot be modified.
  2602. * @}
  2603. */