core.api.php 115 KB
 webchick committed Mar 12, 2014 1 2 3 4 5 6 7 8 9 10 11 get('system.cron_last'); * // Set the cron run time to the current request time.  194  * $state->set('system.cron_last', REQUEST_TIME);  195  * @endcode  webchick committed Mar 12, 2014 196  *  xjm committed May 24, 2015 197  * For more on the State API, see https://www.drupal.org/developing/api/8/state  198 199 200 201 202 203 204 205 206  * @} */ /** * @defgroup config_api Configuration API * @{ * Information about the Configuration API. * * The Configuration API is one of several methods in Drupal for storing  207  * information. See the @link info_types Information types topic @endlink for  208 209  * an overview of the different types of information. The sections below have * more information about the configuration API; see  xjm committed May 24, 2015 210  * https://www.drupal.org/developing/api/8/configuration for more details.  211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227  * * @section sec_storage Configuration storage * In Drupal, there is a concept of the "active" configuration, which is the * configuration that is currently in use for a site. The storage used for the * active configuration is configurable: it could be in the database, in files * in a particular directory, or in other storage backends; the default storage * is in the database. Module developers must use the configuration API to * access the active configuration, rather than being concerned about the * details of where and how it is stored. * * Configuration is divided into individual objects, each of which has a * unique name or key. Some modules will have only one configuration object, * typically called 'mymodule.settings'; some modules will have many. Within * a configuration object, configuration settings have data types (integer, * string, Boolean, etc.) and settings can also exist in a nested hierarchy, * known as a "mapping". *  228 229 230 231  * Configuration can also be overridden on a global, per-language, or * per-module basis. See https://www.drupal.org/node/1928898 for more * information. *  232 233 234 235  * @section sec_yaml Configuration YAML files * Whether or not configuration files are being used for the active * configuration storage on a particular site, configuration files are always * used for:  webchick committed Aug 28, 2015 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252  * - Defining the default configuration for an extension (module, theme, or * profile), which is imported to the active storage when the extension if * enabled. These configuration items are located in the config/install * sub-directory of the extension. Note that changes to this configuration * after a module or theme is already enabled have no effect; to make a * configuration change after a module or theme is enabled, you would need to * uninstall/reinstall or use a hook_update_N() function. * - Defining optional configuration for a module or theme. Optional * configuration items are located in the config/optional sub-directory of the * extension. These configuration items have dependencies that are not * explicit dependencies of the extension, so they are only installed if all * dependencies are met. For example, in the scenario that module A defines a * dependency which requires module B, but module A is installed first and * module B some time later, then module A's config/optional directory will be * scanned at that time for newly met dependencies, and the configuration will * be installed then. If module B is never installed, the configuration item * will not be installed either.  253 254  * - Exporting and importing configuration. *  alexpott committed Apr 02, 2015 255 256  * The file storage format for configuration information in Drupal is * @link http://en.wikipedia.org/wiki/YAML YAML files. @endlink Configuration is  257 258 259 260 261 262  * divided into files, each containing one configuration object. The file name * for a configuration object is equal to the unique name of the configuration, * with a '.yml' extension. The default configuration files for each module are * placed in the config/install directory under the top-level module directory, * so look there in most Core modules for examples. *  alexpott committed Apr 02, 2015 263  * @section sec_schema Configuration schema and translation  264 265 266 267 268  * Each configuration file has a specific structure, which is expressed as a * YAML-based configuration schema. The configuration schema details the * structure of the configuration, its data types, and which of its values need * to be translatable. Each module needs to define its configuration schema in * files in the config/schema directory under the top-level module directory, so  alexpott committed Apr 02, 2015 269 270 271 272 273 274 275  * look there in most Core modules for examples. * * Configuration can be internationalized; see the * @link i18n Internationalization topic @endlink for more information. Data * types label, text, and date_format in configuration schema are translatable; * string is non-translatable text (the 'translatable' property on a schema * data type definition indicates that it is translatable).  276 277 278 279 280 281 282 283 284 285 286 287 288 289 290  * * @section sec_simple Simple configuration * The simple configuration API should be used for information that will always * have exactly one copy or version. For instance, if your module has a * setting that is either on or off, then this is only defined once, and it * would be a Boolean-valued simple configuration setting. * * The first task in using the simple configuration API is to define the * configuration file structure, file name, and schema of your settings (see * @ref sec_yaml above). Once you have done that, you can retrieve the * active configuration object that corresponds to configuration file * mymodule.foo.yml with a call to: * @code *$config = \Drupal::config('mymodule.foo'); * @endcode  webchick committed Mar 12, 2014 291  *  292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319  * This will be an object of class \Drupal\Core\Config\Config, which has methods * for getting and setting configuration information. For instance, if your * YAML file structure looks like this: * @code * enabled: '0' * bar: * baz: 'string1' * boo: 34 * @endcode * you can make calls such as: * @code * // Get a single value. * $enabled =$config->get('enabled'); * // Get an associative array. * $bar =$config->get('bar'); * // Get one element of the array. * $bar_baz =$config->get('bar.baz'); * // Update a value. Nesting works the same as get(). * $config->set('bar.baz', 'string2'); * // Nothing actually happens with set() until you call save(). *$config->save(); * @endcode * * @section sec_entity Configuration entities * In contrast to the simple configuration settings described in the previous * section, if your module allows users to create zero or more items (where * "items" are things like content type definitions, view definitions, and the * like), then you need to define a configuration entity type to store your  320  * configuration. Creating an entity type, loading entities, and querying them  321 322 323 324 325 326 327 328 329 330 331 332 333 334 335  * are outlined in the @link entity_api Entity API topic. @endlink Here are a * few additional steps and notes specific to configuration entities: * - For examples, look for classes that implement * \Drupal\Core\Config\Entity\ConfigEntityInterface -- one good example is * the \Drupal\user\Entity\Role entity type. * - In the entity type annotation, you will need to define a 'config_prefix' * string. When Drupal stores a configuration item, it will be given a name * composed of your module name, your chosen config prefix, and the ID of * the individual item, separated by '.'. For example, in the Role entity, * the config prefix is 'role', so one configuration item might be named * user.role.anonymous, with configuration file user.role.anonymous.yml. * - You will need to define the schema for your configuration in your * modulename.schema.yml file, with an entry for 'modulename.config_prefix.*'. * For example, for the Role entity, the file user.schema.yml has an entry * user.role.*; see @ref sec_yaml above for more information.  webchick committed Aug 28, 2015 336 337  * - Your module can provide default/optional configuration entities in YAML * files; see @ref sec_yaml above for more information.  338 339 340 341  * - Some configuration entities have dependencies on other configuration * entities, and module developers need to consider this so that configuration * can be imported, uninstalled, and synchronized in the right order. For * example, a field display configuration entity would need to depend on  webchick committed Sep 19, 2014 342 343  * field configuration, which depends on field and bundle configuration. * Configuration entity classes expose dependencies by overriding the  344 345  * \Drupal\Core\Config\Entity\ConfigEntityInterface::calculateDependencies() * method.  alexpott committed Jan 22, 2015 346 347 348 349 350 351 352 353 354 355 356 357 358 359  * - On routes for paths staring with '/admin' or otherwise designated as * administration paths (such as node editing when it is set as an admin * operation), if they have configuration entity placeholders, configuration * entities are normally loaded in their original language, without * translations or other overrides. This is usually desirable, because most * admin paths are for editing configuration, and you need that to be in the * source language and to lack possibly dynamic overrides. If for some reason * you need to have your configuration entity loaded in the currently-selected * language on an admin path (for instance, if you go to * example.com/es/admin/your_path and you need the entity to be in Spanish), * then you can add a 'with_config_overrides' parameter option to your route. * The same applies if you need to load the entity with overrides (or * translated) on an admin path like '/node/add/article' (when configured to * be an admin path). Here's an example using the configurable_language config  Dries committed Nov 26, 2014 360 361 362 363 364 365 366 367 368 369  * entity: * @code * mymodule.myroute: * path: '/admin/mypath/{configurable_language}' * defaults: * _controller: '\Drupal\mymodule\MyController::myMethod' * options: * parameters: * configurable_language: * type: entity:configurable_language  alexpott committed Jan 22, 2015 370  * with_config_overrides: TRUE  Dries committed Nov 26, 2014 371 372 373 374 375  * @endcode * With the route defined this way, the $configurable_language parameter to * your controller method will come in translated to the current language. * Without the parameter options section, it would be in the original * language, untranslated.  webchick committed Jun 23, 2014 376 377 378  * * @see i18n *  webchick committed Mar 12, 2014 379 380 381 382 383 384 385 386  * @} */ /** * @defgroup cache Cache API * @{ * Information about the Drupal Cache API *  webchick committed Mar 20, 2014 387 388 389 390 391  * @section basics Basics * * Note: If not specified, all of the methods mentioned here belong to * \Drupal\Core\Cache\CacheBackendInterface. *  alexpott committed Jun 23, 2015 392 393 394  * The Cache API is used to store data that takes a long time to compute. * Caching can either be permanent or valid only for a certain timespan, and * the cache can contain any type of data.  webchick committed Mar 20, 2014 395 396 397 398 399 400 401  * * To use the Cache API: * - Request a cache object through \Drupal::cache() or by injecting a cache * service. * - Define a Cache ID (cid) value for your data. A cid is a string, which must * contain enough information to uniquely identify the data. For example, if * your data contains translated strings, then your cid value must include the  xjm committed May 24, 2015 402  * interface text language selected for page.  webchick committed Mar 20, 2014 403 404 405 406 407 408 409 410  * - Call the get() method to attempt a cache read, to see if the cache already * contains your data. * - If your data is not already in the cache, compute it and add it to the * cache using the set() method. The third argument of set() can be used to * control the lifetime of your cache item. * * Example: * @code  catch committed Oct 13, 2014 411  *$cid = 'mymodule_example:' . \Drupal::languageManager()->getCurrentLanguage()->getId();  webchick committed Mar 20, 2014 412 413 414 415 416 417 418 419 420 421 422  * * $data = NULL; * if ($cache = \Drupal::cache()->get($cid)) { *$data = $cache->data; * } * else { *$data = my_module_complicated_calculation(); * \Drupal::cache()->set($cid,$data); * } * @endcode *  jhodgdon committed Mar 28, 2014 423 424 425 426 427 428  * Note the use of $data and$cache->data in the above example. Calls to * \Drupal::cache()->get() return a record that contains the information stored * by \Drupal::cache()->set() in the data property as well as additional meta * information about the cached data. In order to make use of the cached data * you can access it via $cache->data. *  webchick committed Mar 20, 2014 429 430 431 432 433 434 435  * @section bins Cache bins * * Cache storage is separated into "bins", each containing various cache items. * Each bin can be configured separately; see @ref configuration. * * When you request a cache object, you can specify the bin name in your call to * \Drupal::cache(). Alternatively, you can request a bin by getting service  436 437  * "cache.nameofbin" from the container. The default bin is called "default", with * service name "cache.default", it is used to store common and frequently used  438  * caches.  webchick committed Mar 20, 2014 439  *  catch committed Mar 26, 2014 440 441 442 443 444  * Other common cache bins are the following: * - bootstrap: Small caches needed for the bootstrap on every request. * - render: Contains cached HTML strings like cached pages and blocks, can * grow to large size. * - data: Contains data that can vary by path or similar context.  445 446  * - discovery: Contains cached discovery data for things such as plugins, * views_data, or YAML discovered data such as library info.  webchick committed Mar 20, 2014 447 448 449 450 451 452 453 454 455  * * A module can define a cache bin by defining a service in its * modulename.services.yml file as follows (substituting the desired name for * "nameofbin"): * @code * cache.nameofbin: * class: Drupal\Core\Cache\CacheBackendInterface * tags: * - { name: cache.bin }  456  * factory: cache_factory:get  webchick committed Mar 20, 2014 457 458  * arguments: [nameofbin] * @endcode  alexpott committed Aug 01, 2014 459 460  * See the @link container Services topic @endlink for more on defining * services.  webchick committed Mar 20, 2014 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488  * * @section delete Deletion * * There are two ways to remove an item from the cache: * - Deletion (using delete(), deleteMultiple() or deleteAll()) permanently * removes the item from the cache. * - Invalidation (using invalidate(), invalidateMultiple() or invalidateAll()) * is a "soft" delete that only marks items as "invalid", meaning "not fresh" * or "not fresh enough". Invalid items are not usually returned from the * cache, so in most ways they behave as if they have been deleted. However, * it is possible to retrieve invalid items, if they have not yet been * permanently removed by the garbage collector, by passing TRUE as the second * argument for get($cid, $allow_invalid). * * Use deletion if a cache item is no longer useful; for instance, if the item * contains references to data that has been deleted. Use invalidation if the * cached item may still be useful to some callers until it has been updated * with fresh data. The fact that it was fresh a short while ago may often be * sufficient. * * Invalidation is particularly useful to protect against stampedes. Rather than * having multiple concurrent requests updating the same cache item when it * expires or is deleted, there can be one request updating the cache, while the * other requests can proceed using the stale value. As soon as the cache item * has been updated, all future requests will use the updated value. * * @section tags Cache Tags *  webchick committed Apr 06, 2015 489 490 491 492 493 494 495  * The fourth argument of the set() method can be used to specify cache tags, * which are used to identify which data is included in each cache item. A cache * item can have multiple cache tags (an array of cache tags), and each cache * tag is a string. The convention is to generate cache tags of the form * [prefix]:[suffix]. Usually, you'll want to associate the cache tags of * entities, or entity listings. You won't have to manually construct cache tags * for them — just get their cache tags via  alexpott committed Jun 23, 2015 496  * \Drupal\Core\Cache\CacheableDependencyInterface::getCacheTags() and  alexpott committed Jan 11, 2015 497  * \Drupal\Core\Entity\EntityTypeInterface::getListCacheTags().  webchick committed Apr 06, 2015 498 499 500  * Data that has been tagged can be invalidated as a group: no matter the Cache * ID (cid) of the cache item, no matter in which cache bin a cache item lives; * as long as it is tagged with a certain cache tag, it will be invalidated.  alexpott committed Apr 12, 2014 501 502 503 504 505 506 507 508 509 510 511 512  * * Because of that, cache tags are a solution to the cache invalidation problem: * - For caching to be effective, each cache item must only be invalidated when * absolutely necessary. (i.e. maximizing the cache hit ratio.) * - For caching to be correct, each cache item that depends on a certain thing * must be invalidated whenever that certain thing is modified. * * A typical scenario: a user has modified a node that appears in two views, * three blocks and on twelve pages. Without cache tags, we couldn't possibly * know which cache items to invalidate, so we'd have to invalidate everything: * we had to sacrifice effectiveness to achieve correctness. With cache tags, we * can have both.  webchick committed Mar 20, 2014 513 514 515 516 517  * * Example: * @code * // A cache item with nodes, users, and some custom module data. *$tags = array(  alexpott committed Jan 11, 2015 518 519 520 521  * 'my_custom_tag', * 'node:1', * 'node:3', * 'user:7',  webchick committed Mar 20, 2014 522 523 524  * ); * \Drupal::cache()->set($cid,$data, CacheBackendInterface::CACHE_PERMANENT, $tags); *  525  * // Invalidate all cache items with certain tags.  catch committed Sep 25, 2014 526  * \Drupal\Core\Cache\Cache::invalidateTags(array('user:1'));  webchick committed Mar 20, 2014 527 528  * @endcode *  alexpott committed Apr 12, 2014 529 530 531 532 533 534 535 536  * Drupal is a content management system, so naturally you want changes to your * content to be reflected everywhere, immediately. That's why we made sure that * every entity type in Drupal 8 automatically has support for cache tags: when * you save an entity, you can be sure that the cache items that have the * corresponding cache tags will be invalidated. * This also is the case when you define your own entity types: you'll get the * exact same cache tag invalidation as any of the built-in entity types, with * the ability to override any of the default behavior if needed.  alexpott committed Jun 23, 2015 537  * See \Drupal\Core\Cache\CacheableDepenencyInterface::getCacheTags(),  webchick committed Oct 01, 2014 538  * \Drupal\Core\Entity\EntityTypeInterface::getListCacheTags(),  alexpott committed Apr 12, 2014 539 540  * \Drupal\Core\Entity\Entity::invalidateTagsOnSave() and * \Drupal\Core\Entity\Entity::invalidateTagsOnDelete().  webchick committed Mar 20, 2014 541  *  alexpott committed Jun 23, 2015 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564  * @section context Cache contexts * * Some computed data depends on contextual data, such as the user roles of the * logged-in user who is viewing a page, the language the page is being rendered * in, the theme being used, etc. When caching the output of such a calculation, * you must cache each variation separately, along with information about which * variation of the contextual data was used in the calculatation. The next time * the computed data is needed, if the context matches that for an existing * cached data set, the cached data can be reused; if no context matches, a new * data set can be calculated and cached for later use. * * Cache contexts are services tagged with 'cache.context', whose classes * implement \Drupal\Core\Cache\Context\CacheContextInterface. See * https://www.drupal.org/developing/api/8/cache/contexts for more information * on cache contexts, including a list of the contexts that exist in Drupal * core, and information on how to define your own contexts. See the * @link container Services and the Dependency Injection Container @endlink * topic for more information about services. * * Typically, the cache context is specified as part of the #cache property * of a render array; see the Caching section of the * @link theme_render Render API overview topic @endlink for details. *  webchick committed Mar 20, 2014 565 566  * @section configuration Configuration *  jhodgdon committed Mar 28, 2014 567 568 569  * By default cached data is stored in the database. This can be configured * though so that all cached data, or that of an individual cache bin, uses a * different cache backend, such as APC or Memcache, for storage.  webchick committed Mar 20, 2014 570  *  571 572 573  * In a settings.php file, you can override the service used for a particular * cache bin. For example, if your service implementation of * \Drupal\Core\Cache\CacheBackendInterface was called cache.custom, the  catch committed Mar 26, 2014 574  * following line would make Drupal use it for the 'cache_render' bin:  webchick committed Mar 20, 2014 575  * @code  576  *$settings['cache']['bins']['render'] = 'cache.custom';  webchick committed Mar 20, 2014 577 578 579 580 581  * @endcode * * Additionally, you can register your cache implementation to be used by * default for all cache bins with: * @code  582  * $settings['cache']['default'] = 'cache.custom';  webchick committed Mar 20, 2014 583  * @endcode  webchick committed Mar 12, 2014 584  *  alexpott committed Aug 06, 2015 585 586 587  * Finally, you can chain multiple cache backends together, see * \Drupal\Core\Cache\ChainedFastBackend and \Drupal\Core\Cache\BackendChain. *  xjm committed May 24, 2015 588  * @see https://www.drupal.org/node/1884796  webchick committed Mar 12, 2014 589 590 591 592  * @} */ /**  593  * @defgroup user_api User accounts, permissions, and roles  webchick committed Mar 12, 2014 594 595 596  * @{ * API for user accounts, access checking, roles, and permissions. *  jhodgdon committed Oct 02, 2014 597  * @section sec_overview Overview and terminology  598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626  * Drupal's permission system is based on the concepts of accounts, roles, * and permissions. * * Users (site visitors) have accounts, which include a user name, an email * address, a password (or some other means of authentication), and possibly * other fields (if defined on the site). Anonymous users have an implicit * account that does not have a real user name or any account information. * * Each user account is assigned one or more roles. The anonymous user account * automatically has the anonymous user role; real user accounts * automatically have the authenticated user role, plus any roles defined on * the site that they have been assigned. * * Each role, including the special anonymous and authenticated user roles, is * granted one or more named permissions, which allow them to perform certain * tasks or view certain content on the site. It is possible to designate a * role to be the "administrator" role; if this is set up, this role is * automatically granted all available permissions whenever a module is * enabled that defines permissions. * * All code in Drupal that allows users to perform tasks or view content must * check that the current user has the correct permission before allowing the * action. In the standard case, access checking consists of answering the * question "Does the current user have permission 'foo'?", and allowing or * denying access based on the answer. Note that access checking should nearly * always be done at the permission level, not by checking for a particular role * or user ID, so that site administrators can set up user accounts and roles * appropriately for their particular sites. *  jhodgdon committed Jul 30, 2014 627  * @section sec_define Defining permissions  alexpott committed Jan 21, 2015 628 629  * Modules define permissions via a$module.permissions.yml file. See * \Drupal\user\PermissionHandler for documentation of permissions.yml files.  630  *  jhodgdon committed Jul 30, 2014 631  * @section sec_access Access permission checking  632 633 634 635 636 637 638 639  * Depending on the situation, there are several methods for ensuring that * access checks are done properly in Drupal: * - Routes: When you register a route, include a 'requirements' section that * either gives the machine name of the permission that is needed to visit the * URL of the route, or tells Drupal to use an access check method or service * to check access. See the @link menu Routing topic @endlink for more * information. * - Entities: Access for various entity operations is designated either with  alexpott committed Aug 07, 2014 640 641 642  * simple permissions or access control handler classes in the entity * annotation. See the @link entity_api Entity API topic @endlink for more * information.  643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658  * - Other code: There is a 'current_user' service, which can be injected into * classes to provide access to the current user account (see the * @link container Services and Dependency Injection topic @endlink for more * information on dependency injection). In code that cannot use dependency * injection, you can access this service and retrieve the current user * account object by calling \Drupal::currentUser(). Once you have a user * object for the current user (implementing \Drupal\user\UserInterface), you * can call inherited method * \Drupal\Core\Session\AccountInterface::hasPermission() to check * permissions, or pass this object into other functions/methods. * - Forms: Each element of a form array can have a Boolean '#access' property, * which determines whether that element is visible and/or usable. This is a * common need in forms, so the current user service (described above) is * injected into the form base class as method * \Drupal\Core\Form\FormBase::currentUser(). *  jhodgdon committed Jul 30, 2014 659  * @section sec_entities User and role objects  660 661 662 663 664 665 666 667 668 669 670 671 672  * User objects in Drupal are entity items, implementing * \Drupal\user\UserInterface. Role objects in Drupal are also entity items, * implementing \Drupal\user\RoleInterface. See the * @link entity_api Entity API topic @endlink for more information about * entities in general (including how to load, create, modify, and query them). * * Roles often need to be manipulated in automated test code, such as to add * permissions to them. Here's an example: * @code * $role = \Drupal\user\Entity\Role::load('authenticated'); *$role->grantPermission('access comments'); * $role->save(); * @endcode  webchick committed Mar 12, 2014 673  *  674 675 676 677 678 679  * Other important interfaces: * - \Drupal\Core\Session\AccountInterface: The part of UserInterface that * deals with access checking. In writing code that checks access, your * method parameters should use this interface, not UserInterface. * - \Drupal\Core\Session\AccountProxyInterface: The interface for the * current_user service (described above).  webchick committed Mar 12, 2014 680 681 682 683 684 685 686 687  * @} */ /** * @defgroup container Services and Dependency Injection Container * @{ * Overview of the Dependency Injection Container and Services. *  alexpott committed Aug 01, 2014 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702  * @section sec_overview Overview of container, injection, and services * The Services and Dependency Injection Container concepts have been adopted by * Drupal from the @link http://symfony.com/ Symfony framework. @endlink A * "service" (such as accessing the database, sending email, or translating user * interface text) is defined (given a name and an interface or at least a * class that defines the methods that may be called), and a default class is * defined to provide the service. These two steps must be done together, and * can be done by Drupal Core or a module. Other modules can then define * alternative classes to provide the same services, overriding the default * classes. Classes and functions that need to use the service should always * instantiate the class via the dependency injection container (also known * simply as the "container"), rather than instantiating a particular service * provider class directly, so that they get the correct class (default or * overridden). *  xjm committed May 24, 2015 703  * See https://www.drupal.org/node/2133171 for more detailed information on  alexpott committed Aug 01, 2014 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725  * services and the dependency injection container. * * @section sec_discover Discovering existing services * Drupal core defines many core services in the core.services.yml file (in the * top-level core directory). Some Drupal Core modules and contributed modules * also define services in modulename.services.yml files. API reference sites * (such as https://api.drupal.org) generate lists of all existing services from * these files, or you can look through the individual files manually. * * A typical service definition in a *.services.yml file looks like this: * @code * path.alias_manager: * class: Drupal\Core\Path\AliasManager * arguments: ['@path.crud', '@path.alias_whitelist', '@language_manager'] * @endcode * Some services use other services as factories; a typical service definition * is: * @code * cache.entity: * class: Drupal\Core\Cache\CacheBackendInterface * tags: * - { name: cache.bin }  726  * factory: cache_factory:get  alexpott committed Aug 01, 2014 727 728  * arguments: [entity] * @endcode  webchick committed Mar 12, 2014 729  *  alexpott committed Aug 01, 2014 730 731 732 733 734 735 736 737 738 739 740 741  * The first line of a service definition gives the unique machine name of the * service. This is often prefixed by the module name if provided by a module; * however, by convention some service names are prefixed by a group name * instead, such as cache.* for cache bins and plugin.manager.* for plugin * managers. * * The class line either gives the default class that provides the service, or * if the service uses a factory class, the interface for the service. If the * class depends on other services, the arguments line lists the machine * names of the dependencies (preceded by '@'); objects for each of these * services are instantiated from the container and passed to the class * constructor when the service class is instantiated. Other arguments can also  xjm committed May 24, 2015 742  * be passed in; see the section at https://www.drupal.org/node/2133171 for more  alexpott committed Aug 01, 2014 743 744 745 746 747  * detailed information. * * Services using factories can be defined as shown in the above example, if the * factory is itself a service. The factory can also be a class; details of how * to use service factories can be found in the section at  xjm committed May 24, 2015 748  * https://www.drupal.org/node/2133171.  alexpott committed Aug 01, 2014 749 750 751 752 753 754 755 756 757 758 759 760 761 762  * * @section sec_container Accessing a service through the container * As noted above, if you need to use a service in your code, you should always * instantiate the service class via a call to the container, using the machine * name of the service, so that the default class can be overridden. There are * several ways to make sure this happens: * - For service-providing classes, see other sections of this documentation * describing how to pass services as arguments to the constructor. * - Plugin classes, controllers, and similar classes have create() or * createInstance() methods that are used to create an instance of the class. * These methods come from different interfaces, and have different * arguments, but they all include an argument$container of type * \Symfony\Component\DependencyInjection\ContainerInterface. * If you are defining one of these classes, in the create() or  webchick committed Apr 06, 2015 763 764 765  * createInstance() method, call $container->get('myservice.name') to * instantiate a service. The results of these calls are generally passed to * the class constructor and saved as member variables in the class.  alexpott committed Aug 01, 2014 766 767 768 769 770 771 772  * - For functions and class methods that do not have access to either of * the above methods of dependency injection, you can use service location to * access services, via a call to the global \Drupal class. This class has * special methods for accessing commonly-used services, or you can call a * generic method to access any service. Examples: * @code * // Retrieve the entity.manager service object (special method exists).  webchick committed Aug 26, 2014 773  *$manager = \Drupal::entityManager();  alexpott committed Aug 01, 2014 774  * // Retrieve the service object for machine name 'foo.bar'.  webchick committed Aug 26, 2014 775  * $foobar = \Drupal::service('foo.bar');  alexpott committed Aug 01, 2014 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807  * @endcode * * As a note, you should always use dependency injection (via service arguments * or create()/createInstance() methods) if possible to instantiate services, * rather than service location (via the \Drupal class), because: * - Dependency injection facilitates writing unit tests, since the container * argument can be mocked and the create() method can be bypassed by using * the class constructor. If you use the \Drupal class, unit tests are much * harder to write and your code has more dependencies. * - Having the service interfaces on the class constructor and member variables * is useful for IDE auto-complete and self-documentation. * * @section sec_define Defining a service * If your module needs to define a new service, here are the steps: * - Choose a unique machine name for your service. Typically, this should * start with your module name. Example: mymodule.myservice. * - Create a PHP interface to define what your service does. * - Create a default class implementing your interface that provides your * service. If your class needs to use existing services (such as database * access), be sure to make these services arguments to your class * constructor, and save them in member variables. Also, if the needed * services are provided by other modules and not Drupal Core, you'll want * these modules to be dependencies of your module. * - Add an entry to a modulename.services.yml file for the service. See * @ref sec_discover above, or existing *.services.yml files in Core, for the * syntax; it will start with your machine name, refer to your default class, * and list the services that need to be passed into your constructor. * * Services can also be defined dynamically, as in the * \Drupal\Core\CoreServiceProvider class, but this is less common for modules. * * @section sec_tags Service tags  webchick committed Dec 22, 2014 808 809  * Some services have tags, which are defined in the service definition. See * @link service_tag Service Tags @endlink for usage.  alexpott committed Aug 01, 2014 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835  * * @section sec_injection Overriding the default service class * Modules can override the default classes used for services. Here are the * steps: * - Define a class in the top-level namespace for your module * (Drupal\my_module), whose name is the camel-case version of your module's * machine name followed by "ServiceProvider" (for example, if your module * machine name is my_module, the class must be named * MyModuleServiceProvider). * - The class needs to implement * \Drupal\Core\DependencyInjection\ServiceModifierInterface, which is * typically done by extending * \Drupal\Core\DependencyInjection\ServiceProviderBase. * - The class needs to contain one method: alter(). This method does the * actual work of telling Drupal to use your class instead of the default. * Here's an example: * @code * public function alter(ContainerBuilder$container) { * // Override the language_manager class with a new class. * $definition =$container->getDefinition('language_manager'); * $definition->setClass('Drupal\my_module\MyLanguageManager'); * } * @endcode * Note that$container here is an instance of * \Drupal\Core\DependencyInjection\ContainerBuilder. *  xjm committed May 24, 2015 836  * @see https://www.drupal.org/node/2133171  alexpott committed Aug 01, 2014 837 838 839 840 841  * @see core.services.yml * @see \Drupal * @see \Symfony\Component\DependencyInjection\ContainerInterface * @see plugin_api * @see menu  webchick committed Mar 12, 2014 842 843 844 845 846 847  * @} */ /** * @defgroup typed_data Typed Data API * @{  webchick committed Jun 16, 2014 848 849  * API for describing data based on a set of available data types. *  850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875  * PHP has data types, such as int, string, float, array, etc., and it is an * object-oriented language that lets you define classes and interfaces. * However, in some cases, it is useful to be able to define an abstract * type (as in an interface, free of implementation details), that still has * properties (which an interface cannot) as well as meta-data. The Typed Data * API provides this abstraction. * * @section sec_overview Overview * Each data type in the Typed Data API is a plugin class (annotation class * example: \Drupal\Core\TypedData\Annotation\DataType); these plugins are * managed by the typed_data_manager service (by default * \Drupal\Core\TypedData\TypedDataManager). Each data object encapsulates a * single piece of data, provides access to the metadata, and provides * validation capability. Also, the typed data plugins have a shorthand * for easily accessing data values, described in @ref sec_tree. * * The metadata of a data object is defined by an object based on a class called * the definition class (see \Drupal\Core\TypedData\DataDefinitionInterface). * The class used can vary by data type and can be specified in the data type's * plugin definition, while the default is set in the $definition_class property * of the annotation class. The default class is * \Drupal\Core\TypedData\DataDefinition. For data types provided by a plugin * deriver, the plugin deriver can set the definition_class property too. * The metadata object provides information about the data, such as the data * type, whether it is translatable, the names of its properties (for complex * types), and who can access it.  webchick committed Jun 16, 2014 876  *  xjm committed May 24, 2015 877  * See https://www.drupal.org/node/1794140 for more information about the Typed  webchick committed Jun 16, 2014 878 879  * Data API. *  880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954  * @section sec_varieties Varieties of typed data * There are three kinds of typed data: primitive, complex, and list. * * @subsection sub_primitive Primitive data types * Primitive data types wrap PHP data types and also serve as building blocks * for complex and list typed data. Each primitive data type has an interface * that extends \Drupal\Core\TypedData\PrimitiveInterface, with getValue() * and setValue() methods for accessing the data value, and a default plugin * implementation. Here's a list: * - \Drupal\Core\TypedData\Type\IntegerInterface: Plugin ID integer, * corresponds to PHP type int. * - \Drupal\Core\TypedData\Type\StringInterface: Plugin ID string, * corresponds to PHP type string. * - \Drupal\Core\TypedData\Type\FloatInterface: Plugin ID float, * corresponds to PHP type float. * - \Drupal\Core\TypedData\Type\BooleanInterface: Plugin ID bool, * corresponds to PHP type bool. * - \Drupal\Core\TypedData\Type\BinaryInterface: Plugin ID binary, * corresponds to a PHP file resource. * - \Drupal\Core\TypedData\Type\UriInterface: Plugin ID uri. * * @subsection sec_complex Complex data * Complex data types, with interface * \Drupal\Core\TypedData\ComplexDataInterface, represent data with named * properties; the properties can be accessed with get() and set() methods. * The value of each property is itself a typed data object, which can be * primitive, complex, or list data. * * The base type for most complex data is the * \Drupal\Core\TypedData\Plugin\DataType\Map class, which represents an * associative array. Map provides its own definition class in the annotation, * \Drupal\Core\TypedData\MapDataDefinition, and most complex data classes * extend this class. The getValue() and setValue() methods on the Map class * enforce the data definition and its property structure. * * The Drupal Field API uses complex typed data for its field items, with * definition class \Drupal\Core\Field\TypedData\FieldItemDataDefinition. * * @section sec_list Lists * List data types, with interface \Drupal\Core\TypedData\ListInterface, * represent data that is an ordered list of typed data, all of the same type. * More precisely, the plugins in the list must have the same base plugin ID; * however, some types (for example field items and entities) are provided by * plugin derivatives and the sub IDs can be different. * * @section sec_tree Tree handling * Typed data allows you to use shorthand to get data values nested in the * implicit tree structure of the data. For example, to get the value from * an entity field item, the Entity Field API allows you to call: * @code *$value = $entity->fieldName->propertyName; * @endcode * This is really shorthand for: * @code *$field_item_list = $entity->get('fieldName'); *$field_item = $field_item_list->get(0); *$property = $field_item->get('propertyName'); *$value = $property->getValue(); * @endcode * Some notes: * -$property, $field_item, and$field_item_list are all typed data objects, * while $value is a raw PHP value. * - You can call$property->getParent() to get $field_item, *$field_item->getParent() to get $field_item_list, or *$field_item_list->getParent() to get $typed_entity ($entity wrapped in a * typed data object). $typed_entity->getParent() is NULL. * - For all of these ->getRoot() returns$typed_entity. * - The langcode property is on $field_item_list, but you can access it * on$property as well, so that all items will report the same langcode. * - When the value of $property is changed by calling$property->setValue(), * $property->onChange() will fire, which in turn calls the parent object's * onChange() method and so on. This allows parent objects to react upon * changes of contained properties or list items. * * @section sec_defining Defining data types  webchick committed Jun 16, 2014 955 956 957  * To define a new data type: * - Create a class that implements one of the Typed Data interfaces. * Typically, you will want to extend one of the classes listed in the  958  * sections above as a starting point.  webchick committed Jun 16, 2014 959 960 961 962 963 964 965  * - Make your class into a DataType plugin. To do that, put it in namespace * \Drupal\yourmodule\Plugin\DataType (where "yourmodule" is your module's * short name), and add annotation of type * \Drupal\Core\TypedData\Annotation\DataType to the documentation header. * See the @link plugin_api Plugin API topic @endlink and the * @link annotation Annotations topic @endlink for more information. *  966  * @section sec_using Using data types  webchick committed Jun 16, 2014 967 968 969 970 971 972 973 974  * The data types of the Typed Data API can be used in several ways, once they * have been defined: * - In the Field API, data types can be used as the class in the property * definition of the field. See the @link field Field API topic @endlink for * more information. * - In configuration schema files, you can use the unique ID ('id' annotation) * from any DataType plugin class as the 'type' value for an entry. See the * @link config_api Confuration API topic @endlink for more information.  975 976 977 978 979 980 981 982 983  * - If you need to create a typed data object in code, first get the * typed_data_manager service from the container or by calling * \Drupal::typedDataManager(). Then pass the plugin ID to *$manager::createDataDefinition() to create an appropriate data definition * object. Then pass the data definition object and the value of the data to * $manager::create() to create a typed data object. * * @see plugin_api * @see container  webchick committed Mar 12, 2014 984 985 986 987 988 989 990 991  * @} */ /** * @defgroup testing Automated tests * @{ * Overview of PHPUnit tests and Simpletest tests. *  webchick committed Jun 16, 2014 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022  * The Drupal project has embraced a philosophy of using automated tests, * consisting of both unit tests (which test the functionality of classes at a * low level) and functional tests (which test the functionality of Drupal * systems at a higher level, usually involving web output). The goal is to * have test coverage for all or most of the components and features, and to * run the automated tests before any code is changed or added, to make sure * it doesn't break any existing functionality (regression testing). * * In order to implement this philosophy, developers need to do the following: * - When making a patch to fix a bug, make sure that the bug fix patch includes * a test that fails without the code change and passes with the code change. * This helps reviewers understand what the bug is, demonstrates that the code * actually fixes the bug, and ensures the bug will not reappear due to later * code changes. * - When making a patch to implement a new feature, include new unit and/or * functional tests in the patch. This serves to both demonstrate that the * code actually works, and ensure that later changes do not break the new * functionality. * * @section write_unit Writing PHPUnit tests for classes * PHPUnit tests for classes are written using the industry-standard PHPUnit * framework. Use a PHPUnit test to test functionality of a class if the Drupal * environment (database, settings, etc.) and web browser are not needed for the * test, or if the Drupal environment can be replaced by a "mock" object. To * write a PHPUnit test: * - Define a class that extends \Drupal\Tests\UnitTestCase. * - The class name needs to end in the word Test. * - The namespace must be a subspace/subdirectory of \Drupal\yourmodule\Tests, * where yourmodule is your module's machine name. * - The test class file must be named and placed under the yourmodule/tests/src * directory, according to the PSR-4 standard.  alexpott committed Feb 16, 2015 1023 1024  * - Your test class needs a phpDoc comment block with a description and * a @group annotation, which gives information about the test.  webchick committed Jun 16, 2014 1025 1026 1027  * - Methods in your test class whose names start with 'test' are the actual * test cases. Each one should test a logical subset of the functionality. * For more details, see:  xjm committed May 24, 2015 1028 1029  * - https://www.drupal.org/phpunit for full documentation on how to write * PHPUnit tests for Drupal.  webchick committed Jun 16, 2014 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055  * - http://phpunit.de for general information on the PHPUnit framework. * - @link oo_conventions Object-oriented programming topic @endlink for more * on PSR-4, namespaces, and where to place classes. * * @section write_functional Writing functional tests * Functional tests are written using a Drupal-specific framework that is, for * historical reasons, known as "Simpletest". Use a Simpletest test to test the * functionality of sub-system of Drupal, if the functionality depends on the * Drupal database and settings, or to test the web output of Drupal. To * write a Simpletest test: * - For functional tests of the web output of Drupal, define a class that * extends \Drupal\simpletest\WebTestBase, which contains an internal web * browser and defines many helpful test assertion methods that you can use * in your tests. You can specify modules to be enabled by defining a *$modules member variable -- keep in mind that by default, WebTestBase uses * a "testing" install profile, with a minimal set of modules enabled. * - For functional tests that do not test web output, define a class that * extends \Drupal\simpletest\KernelTestBase. This class is much faster * than WebTestBase, because instead of making a full install of Drupal, it * uses an in-memory pseudo-installation (similar to what the installer and * update scripts use). To use this test class, you will need to create the * database tables you need and install needed modules manually. * - The namespace must be a subspace/subdirectory of \Drupal\yourmodule\Tests, * where yourmodule is your module's machine name. * - The test class file must be named and placed under the yourmodule/src/Tests * directory, according to the PSR-4 standard.  alexpott committed Feb 16, 2015 1056 1057  * - Your test class needs a phpDoc comment block with a description and * a @group annotation, which gives information about the test.  webchick committed Jun 16, 2014 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067  * - You may also override the default setUp() method, which can set be used to * set up content types and similar procedures. * - In some cases, you may need to write a test module to support your test; * put such modules under the yourmodule/tests/modules directory. * - Methods in your test class whose names start with 'test', and which have * no arguments, are the actual test cases. Each one should test a logical * subset of the functionality, and each one runs in a new, isolated test * environment, so it can only rely on the setUp() method, not what has * been set up by other test methods. * For more details, see:  xjm committed May 24, 2015 1068  * - https://www.drupal.org/simpletest for full documentation on how to write  webchick committed Jun 16, 2014 1069 1070 1071 1072 1073 1074 1075  * functional tests for Drupal. * - @link oo_conventions Object-oriented programming topic @endlink for more * on PSR-4, namespaces, and where to place classes. * * @section running Running tests * You can run both Simpletest and PHPUnit tests by enabling the core Testing * module (core/modules/simpletest). Once that module is enabled, tests can be  1076  * run using the core/scripts/run-tests.sh script, using  xjm committed May 24, 2015 1077 1078  * @link https://www.drupal.org/project/drush Drush @endlink, or from the * Testing module user interface.  webchick committed Jun 16, 2014 1079 1080  * * PHPUnit tests can also be run from the command line, using the PHPUnit  xjm committed May 24, 2015 1081  * framework. See https://www.drupal.org/node/2116263 for more information.  webchick committed Mar 12, 2014 1082 1083 1084  * @} */  alexpott committed Jul 21, 2015 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 /** * @defgroup php_assert PHP Runtime Assert Statements * @{ * Use of the assert() statement in Drupal. * * Unit tests also use the term "assertion" to refer to test conditions, so to * avoid confusion the term "runtime assertion" will be used for the assert() * statement throughout the documentation. * * A runtime assertion is a statement that is expected to always be true at * the point in the code it appears at. They are tested using PHP's internal * @link http://www.php.net/assert assert() @endlink statement. If an * assertion is ever FALSE it indicates an error in the code or in module or * theme configuration files. User-provided configuration files should be * verified with standard control structures at all times, not just checked in * development environments with assert() statements on. *  1102  * When runtime assertions fail in PHP 7 an \AssertionError is thrown.  alexpott committed Jul 21, 2015 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133  * Drupal uses an assertion callback to do the same in PHP 5.x so that unit * tests involving runtime assertions will work uniformly across both versions. * * The Drupal project primarily uses runtime assertions to enforce the * expectations of the API by failing when incorrect calls are made by code * under development. While PHP type hinting does this for objects and arrays, * runtime assertions do this for scalars (strings, integers, floats, etc.) and * complex data structures such as cache and render arrays. They ensure that * methods' return values are the documented datatypes. They also verify that * objects have been properly configured and set up by the service container. * Runtime assertions are checked throughout development. They supplement unit * tests by checking scenarios that do not have unit tests written for them, * and by testing the API calls made by all the code in the system. * * When using assert() keep the following in mind: * - Runtime assertions are disabled by default in production and enabled in * development, so they can't be used as control structures. Use exceptions * for errors that can occur in production no matter how unlikely they are. * - Assert() functions in a buggy manner prior to PHP 7. If you do not use a * string for the first argument of the statement but instead use a function * call or expression then that code will be evaluated even when runtime * assertions are turned off. To avoid this you must use a string as the * first argument, and assert will pass this string to the eval() statement. * - Since runtime assertion strings are parsed by eval() use caution when * using them to work with data that may be unsanitized. * * See https://www.drupal.org/node/2492225 for more information on runtime * assertions. * @} */  webchick committed Mar 12, 2014 1134 /**  1135  * @defgroup info_types Information types  webchick committed Mar 12, 2014 1136  * @{  1137  * Types of information in Drupal.  webchick committed Mar 12, 2014 1138  *  1139 1140 1141 1142 1143 1144 1145 1146  * Drupal has several distinct types of information, each with its own methods * for storage and retrieval: * - Content: Information meant to be displayed on your site: articles, basic * pages, images, files, custom blocks, etc. Content is stored and accessed * using @link entity_api Entities @endlink. * - Session: Information about individual users' interactions with the site, * such as whether they are logged in. This is really "state" information, but * it is not stored the same way so it's a separate type here. Session  alexpott committed Jun 05, 2015 1147 1148  * information is available from the Request object. The session implements * \Symfony\Component\HttpFoundation\Session\SessionInterface.  1149 1150 1151 1152 1153 1154 1155 1156 1157 1158  * - State: Information of a temporary nature, generally machine-generated and * not human-edited, about the current state of your site. Examples: the time * when Cron was last run, whether node access permissions need rebuilding, * etc. See @link state_api the State API topic @endlink for more information. * - Configuration: Information about your site that is generally (or at least * can be) human-edited, but is not Content, and is meant to be relatively * permanent. Examples: the name of your site, the content types and views * you have defined, etc. See * @link config_api the Configuration API topic @endlink for more information. *  1159 1160  * @see cache * @see i18n  webchick committed Mar 12, 2014 1161 1162 1163 1164  * @} */ /**  webchick committed Apr 30, 2014 1165  * @defgroup extending Extending and altering Drupal  webchick committed Mar 12, 2014 1166  * @{  alexpott committed Jan 13, 2015 1167  * Overview of extensions and alteration methods for Drupal.  webchick committed Apr 30, 2014 1168  *  alexpott committed Jan 13, 2015 1169  * @section sec_types Types of extensions  webchick committed Apr 30, 2014 1170  * Drupal's core behavior can be extended and altered via these three basic  alexpott committed Jan 13, 2015 1171  * types of extensions:  webchick committed Apr 30, 2014 1172 1173 1174 1175 1176  * - Themes: Themes alter the appearance of Drupal sites. They can include * template files, which alter the HTML markup and other raw output of the * site; CSS files, which alter the styling applied to the HTML; and * JavaScript, Flash, images, and other files. For more information, see the * @link theme_render Theme system and render API topic @endlink and  xjm committed May 24, 2015 1177  * https://www.drupal.org/theme-guide/8  webchick committed Apr 30, 2014 1178 1179  * - Modules: Modules add to or alter the behavior and functionality of Drupal, * by using one or more of the methods listed below. For more information  xjm committed May 24, 2015 1180  * about creating modules, see https://www.drupal.org/developing/modules/8  webchick committed Apr 30, 2014 1181 1182 1183  * - Installation profiles: Installation profiles can be used to * create distributions, which are complete specific-purpose packages of * Drupal including additional modules, themes, and data. For more  alexpott committed Jan 13, 2015 1184  * information, see https://www.drupal.org/developing/distributions.  webchick committed Apr 30, 2014 1185  *  alexpott committed Jan 13, 2015 1186  * @section sec_alter Alteration methods for modules  webchick committed Apr 30, 2014 1187 1188 1189 1190 1191 1192 1193  * Here is a list of the ways that modules can alter or extend Drupal's core * behavior, or the behavior of other modules: * - Hooks: Specially-named functions that a module defines, which are * discovered and called at specific times, usually to alter behavior or data. * See the @link hooks Hooks topic @endlink for more information. * - Plugins: Classes that a module defines, which are discovered and * instantiated at specific times to add functionality. See the  webchick committed Jun 20, 2014 1194  * @link plugin_api Plugin API topic @endlink for more information.  webchick committed Apr 30, 2014 1195 1196 1197 1198  * - Entities: Special plugins that define entity types for storing new types * of content or configuration in Drupal. See the * @link entity_api Entity API topic @endlink for more information. * - Services: Classes that perform basic operations within Drupal, such as  webchick committed Jun 09, 2014 1199  * accessing the database and sending email. See the  webchick committed Apr 30, 2014 1200 1201 1202 1203 1204  * @link container Dependency Injection Container and Services topic @endlink * for more information. * - Routing: Providing or altering "routes", which are URLs that Drupal * responds to, or altering routing behavior with event listener classes. * See the @link menu Routing and menu topic @endlink for more information.  1205 1206 1207 1208  * - Events: Modules can register as event subscribers; when an event is * dispatched, a method is called on each registered subscriber, allowing each * one to react. See the @link events Events topic @endlink for more * information.  alexpott committed Jan 13, 2015 1209 1210 1211 1212 1213 1214 1215  * * @section sec_sample *.info.yml files * Extensions must each be located in a directory whose name matches the short * name (or machine name) of the extension, and this directory must contain a * file named machine_name.info.yml (where machine_name is the machine name of * the extension). See \Drupal\Core\Extension\InfoParserInterface::parse() for * documentation of the format of .info.yml files.  webchick committed Apr 30, 2014 1216 1217 1218 1219  * @} */ /**  webchick committed Jun 20, 2014 1220  * @defgroup plugin_api Plugin API  webchick committed Apr 30, 2014 1221  * @{  webchick committed Jun 20, 2014 1222  * Using the Plugin API  webchick committed Mar 12, 2014 1223  *  webchick committed Jun 20, 2014 1224  * @section sec_overview Overview and terminology  alexpott committed Jan 15, 2015 1225  *  webchick committed Jun 20, 2014 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249  * The basic idea of plugins is to allow a particular module or subsystem of * Drupal to provide functionality in an extensible, object-oriented way. The * controlling module or subsystem defines the basic framework (interface) for * the functionality, and other modules can create plugins (implementing the * interface) with particular behaviors. The controlling module instantiates * existing plugins as needed, and calls methods to invoke their functionality. * Examples of functionality in Drupal Core that use plugins include: the block * system (block types are plugins), the entity/field system (entity types, * field types, field formatters, and field widgets are plugins), the image * manipulation system (image effects and image toolkits are plugins), and the * search system (search page types are plugins). * * Plugins are grouped into plugin types, each generally defined by an * interface. Each plugin type is managed by a plugin manager service, which * uses a plugin discovery method to discover provided plugins of that type and * instantiate them using a plugin factory. * * Some plugin types make use of the following concepts or components: * - Plugin derivatives: Allows a single plugin class to present itself as * multiple plugins. Example: the Menu module provides a block for each * defined menu via a block plugin derivative. * - Plugin mapping: Allows a plugin class to map a configuration string to an * instance, and have the plugin automatically instantiated without writing * additional code.  alexpott committed Oct 17, 2014 1250  * - Plugin collections: Provide a way to lazily instantiate a set of plugin  webchick committed Jun 20, 2014 1251 1252 1253 1254 1255 1256 1257  * instances from a single plugin definition. * * There are several things a module developer may need to do with plugins: * - Define a completely new plugin type: see @ref sec_define below. * - Create a plugin of an existing plugin type: see @ref sec_create below. * - Perform tasks that involve plugins: see @ref sec_use below. *  xjm committed May 24, 2015 1258  * See https://www.drupal.org/developing/api/8/plugins for more detailed  webchick committed Jun 20, 2014 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289  * documentation on the plugin system. There are also topics for a few * of the many existing types of plugins: * - @link block_api Block API @endlink * - @link entity_api Entity API @endlink * - @link field Various types of field-related plugins @endlink * - @link views_plugins Views plugins @endlink (has links to topics covering * various specific types of Views plugins). * - @link search Search page plugins @endlink * * @section sec_define Defining a new plugin type * To define a new plugin type: * - Define an interface for the plugin. This describes the common set of * behavior, and the methods you will call on each plugin class that is * instantiated. Usually this interface will extend one or more of the * following interfaces: * - \Drupal\Component\Plugin\PluginInspectionInterface * - \Drupal\Component\Plugin\ConfigurablePluginInterface * - \Drupal\Component\Plugin\ContextAwarePluginInterface * - \Drupal\Core\Plugin\PluginFormInterface * - \Drupal\Core\Executable\ExecutableInterface * - (optional) Create a base class that provides a partial implementation of * the interface, for the convenience of developers wishing to create plugins * of your type. The base class usually extends * \Drupal\Core\Plugin\PluginBase, or one of the base classes that extends * this class. * - Choose a method for plugin discovery, and define classes as necessary. * See @ref sub_discovery below. * - Create a plugin manager/factory class and service, which will discover and * instantiate plugins. See @ref sub_manager below. * - Use the plugin manager to instantiate plugins. Call methods on your plugin * interface to perform the tasks of your plugin type.  alexpott committed Oct 17, 2014 1290 1291  * - (optional) If appropriate, define a plugin collection. See @ref * sub_collection below for more information.  webchick committed Apr 30, 2014 1292  *  webchick committed Jun 20, 2014 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302  * @subsection sub_discovery Plugin discovery * Plugin discovery is the process your plugin manager uses to discover the * individual plugins of your type that have been defined by your module and * other modules. Plugin discovery methods are classes that implement * \Drupal\Component\Plugin\Discovery\DiscoveryInterface. Most plugin types use * one of the following discovery mechanisms: * - Annotation: Plugin classes are annotated and placed in a defined namespace * subdirectory. Most Drupal Core plugins use this method of discovery. * - Hook: Plugin modules need to implement a hook to tell the manager about * their plugins.  1303  * - YAML: Plugins are listed in YAML files. Drupal Core uses this method for  webchick committed Jun 20, 2014 1304 1305 1306 1307 1308 1309 1310 1311 1312  * discovering local tasks and local actions. This is mainly useful if all * plugins use the same class, so it is kind of like a global derivative. * - Static: Plugin classes are registered within the plugin manager class * itself. Static discovery is only useful if modules cannot define new * plugins of this type (if the list of available plugins is static). * * It is also possible to define your own custom discovery mechanism or mix * methods together. And there are many more details, such as annotation * decorators, that apply to some of the discovery methods. See  xjm committed May 24, 2015 1313  * https://www.drupal.org/developing/api/8/plugins for more details.  webchick committed Jun 20, 2014 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350  * * The remainder of this documentation will assume Annotation-based discovery, * since this is the most common method. * * @subsection sub_manager Defining a plugin manager class and service * To define an annotation-based plugin manager: * - Choose a namespace subdirectory for your plugin. For example, search page * plugins go in directory Plugin/Search under the module namespace. * - Define an annotation class for your plugin type. This class should extend * \Drupal\Component\Annotation\Plugin, and for most plugin types, it should * contain member variables corresponding to the annotations plugins will * need to provide. All plugins have at least $id: a unique string * identifier. * - Define an alter hook for altering the discovered plugin definitions. You * should document the hook in a *.api.php file. * - Define a plugin manager class. This class should implement * \Drupal\Component\Plugin\PluginManagerInterface; most plugin managers do * this by extending \Drupal\Core\Plugin\DefaultPluginManager. If you do * extend the default plugin manager, the only method you will probably need * to define is the class constructor, which will need to call the parent * constructor to provide information about the annotation class and plugin * namespace for discovery, set up the alter hook, and possibly set up * caching. See classes that extend DefaultPluginManager for examples. * - Define a service for your plugin manager. See the * @link container Services topic for more information. @endlink Your service * definition should look something like this, referencing your manager * class and the parent (default) plugin manager service to inherit * constructor arguments: * @code * plugin.manager.mymodule: * class: Drupal\mymodule\MyPluginManager * parent: default_plugin_manager * @endcode * - If your plugin is configurable, you will also need to define the * configuration schema and possibly a configuration entity type. See the * @link config_api Configuration API topic @endlink for more information. *  alexpott committed Oct 17, 2014 1351  * @subsection sub_collection Defining a plugin collection  webchick committed Jun 20, 2014 1352 1353 1354 1355 1356  * Some configurable plugin types allow administrators to create zero or more * instances of each plugin, each with its own configuration. For example, * a single block plugin can be configured several times, to display in * different regions of a theme, with different visibility settings, a * different title, or other plugin-specific settings. To make this possible,  alexpott committed Oct 17, 2014 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366  * a plugin type can make use of what's known as a plugin collection. * * A plugin collection is a class that extends * \Drupal\Component\Plugin\LazyPluginCollection or one of its subclasses; there * are several examples in Drupal Core. If your plugin type uses a plugin * collection, it will usually also have a configuration entity, and the entity * class should implement * \Drupal\Core\Entity\EntityWithPluginCollectionInterface. Again, there are * several examples in Drupal Core; see also the @link config_api Configuration * API topic @endlink for more information about configuration entities.  webchick committed Jun 20, 2014 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390  * * @section sec_create Creating a plugin of an existing type * Assuming the plugin type uses annotation-based discovery, in order to create * a plugin of an existing type, you will be creating a class. This class must: * - Implement the plugin interface, so that it has the required methods * defined. Usually, you'll want to extend the plugin base class, if one has * been provided. * - Have the right annotation in its documentation header. See the * @link annotation Annotation topic @endlink for more information about * annotation. * - Be in the right plugin namespace, in order to be discovered. * Often, the easiest way to make sure this happens is to find an existing * example of a working plugin class of the desired type, and copy it into your * module as a starting point. * * You can also create a plugin derivative, which allows your plugin class * to present itself to the user interface as multiple plugins. To do this, * in addition to the plugin class, you'll need to create a separate plugin * derivative class implementing * \Drupal\Component\Plugin\Derivative\DerivativeInterface. The classes * \Drupal\system\Plugin\Block\SystemMenuBlock (plugin class) and * \Drupal\system\Plugin\Derivative\SystemMenuBlock (derivative class) are a * good example to look at. *  jhodgdon committed Jul 30, 2014 1391  * @section sec_use Performing tasks involving plugins  webchick committed Jun 20, 2014 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402  * Here are the steps to follow to perform a task that involves plugins: * - Locate the machine name of the plugin manager service, and instantiate the * service. See the @link container Services topic @endlink for more * information on how to do this. * - On the plugin manager class, use methods like getDefinition(), * getDefinitions(), or other methods specific to particular plugin managers * to retrieve information about either specific plugins or the entire list of * defined plugins. * - Call the createInstance() method on the plugin manager to instantiate * individual plugin objects. * - Call methods on the plugin objects to perform the desired tasks.  webchick committed Apr 30, 2014 1403 1404  * * @see annotation  webchick committed Mar 12, 2014 1405 1406 1407 1408 1409 1410 1411 1412  * @} */ /** * @defgroup oo_conventions Objected-oriented programming conventions * @{ * PSR-4, namespaces, class naming, and other conventions. *  1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436  * A lot of the PHP code in Drupal is object oriented (OO), making use of * @link http://php.net/manual/language.oop5.php PHP classes, interfaces, and traits @endlink * (which are loosely referred to as "classes" in the rest of this topic). The * following conventions and standards apply to this version of Drupal: * - Each class must be in its own file. * - Classes must be namespaced. If a module defines a class, the namespace * must start with \Drupal\module_name. If it is defined by Drupal Core for * use across many modules, the namespace should be \Drupal\Core or * \Drupal\Component, with the exception of the global class \Drupal. See * https://www.drupal.org/node/1353118 for more about namespaces. * - In order for the PSR-4-based class auto-loader to find the class, it must * be located in a directory corresponding to the namespace. For * module-defined classes, if the namespace is \Drupal\module_name\foo\bar, * then the class goes under the main module directory in directory * src/foo/bar. For Drupal-wide classes, if the namespace is * \Drupal\Core\foo\bar, then it goes in directory * core/lib/Drupal/Core/foo/bar. See https://www.drupal.org/node/2156625 for * more information about PSR-4. * - Some classes have annotations added to their documentation headers. See * the @link annotation Annotation topic @endlink for more information. * - Standard plugin discovery requires particular namespaces and annotation * for most plugin classes. See the * @link plugin_api Plugin API topic @endlink for more information. * - There are project-wide coding standards for OO code, including naming:  xjm committed May 24, 2015 1437  * https://www.drupal.org/node/608152  1438 1439  * - Documentation standards for classes are covered on: * https://www.drupal.org/coding-standards/docs#classes  webchick committed Mar 12, 2014 1440 1441 1442 1443 1444 1445  * @} */ /** * @defgroup best_practices Best practices for developers * @{  1446 1447 1448 1449 1450 1451 1452  * Overview of standards and best practices for developers * * Ideally, all code that is included in Drupal Core and contributed modules, * themes, and distributions will be secure, internationalized, maintainable, * and efficient. In order to facilitate this, the Drupal community has * developed a set of guidelines and standards for developers to follow. Most of * these standards can be found under  xjm committed May 24, 2015 1453  * @link https://www.drupal.org/developing/best-practices Best practices on Drupal.org @endlink  1454 1455  * * Standards and best practices that developers should be aware of include:  xjm committed May 24, 2015 1456  * - Security: https://www.drupal.org/writing-secure-code and the  1457  * @link sanitization Sanitization functions topic @endlink  xjm committed May 24, 2015 1458 1459 1460 1461 1462  * - Coding standards: https://www.drupal.org/coding-standards * and https://www.drupal.org/coding-standards/docs * - Accessibility: https://www.drupal.org/node/1637990 (modules) and * https://www.drupal.org/node/464472 (themes) * - Usability: https://www.drupal.org/ui-standards  1463 1464  * - Internationalization: @link i18n Internationalization topic @endlink * - Automated testing: @link testing Automated tests topic @endlink  webchick committed Mar 12, 2014 1465 1466  * @} */  jhodgdon committed Mar 28, 2014 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486  /** * @defgroup utility Utility classes and functions * @{ * Overview of utility classes and functions for developers. * * Drupal provides developers with a variety of utility functions that make it * easier and more efficient to perform tasks that are either really common, * tedious, or difficult. Utility functions help to reduce code duplication and * should be used in place of one-off code whenever possible. * * @see common.inc * @see file * @see format * @see php_wrappers * @see sanitization * @see transliteration * @see validation * @} */  1487   jhodgdon committed Jul 29, 2014 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 /** * @defgroup hooks Hooks * @{ * Define functions that alter the behavior of Drupal core. * * One way for modules to alter the core behavior of Drupal (or another module) * is to use hooks. Hooks are specially-named functions that a module defines * (this is known as "implementing the hook"), which are discovered and called * at specific times to alter or add to the base behavior or data (this is * known as "invoking the hook"). Each hook has a name (example: * hook_batch_alter()), a defined set of parameters, and a defined return value. * Your modules can implement hooks that are defined by Drupal core or other * modules that they interact with. Your modules can also define their own * hooks, in order to let other modules interact with them. * * To implement a hook: * - Locate the documentation for the hook. Hooks are documented in *.api.php * files, by defining functions whose name starts with "hook_" (these * files and their functions are never loaded by Drupal -- they exist solely * for documentation). The function should have a documentation header, as * well as a sample function body. For example, in the core file * system.api.php, you can find hooks such as hook_batch_alter(). Also, if * you are viewing this documentation on an API reference site, the Core * hooks will be listed in this topic. * - Copy the function to your module's .module file. * - Change the name of the function, substituting your module's short name * (name of the module's directory, and .info.yml file without the extension)  1515  * for the "hook" part of the sample function name. For instance, to implement  jhodgdon committed Jul 29, 2014 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599  * hook_batch_alter(), you would rename it to my_module_batch_alter(). * - Edit the documentation for the function (normally, your implementation * should just have one line saying "Implements hook_batch_alter()."). * - Edit the body of the function, substituting in what you need your module * to do. * * To define a hook: * - Choose a unique name for your hook. It should start with "hook_", followed * by your module's short name. * - Provide documentation in a *.api.php file in your module's main * directory. See the "implementing" section above for details of what this * should contain (parameters, return value, and sample function body). * - Invoke the hook in your module's code. * * To invoke a hook, use methods on * \Drupal\Core\Extension\ModuleHandlerInterface such as alter(), invoke(), * and invokeAll(). You can obtain a module handler by calling * \Drupal::moduleHandler(), or getting the 'module_handler' service on an * injected container. * * @see extending * @see themeable * @see callbacks * @see \Drupal\Core\Extension\ModuleHandlerInterface * @see \Drupal::moduleHandler() * * @} */ /** * @defgroup callbacks Callbacks * @{ * Callback function signatures. * * Drupal's API sometimes uses callback functions to allow you to define how * some type of processing happens. A callback is a function with a defined * signature, which you define in a module. Then you pass the function name as * a parameter to a Drupal API function or return it as part of a hook * implementation return value, and your function is called at an appropriate * time. For instance, when setting up batch processing you might need to * provide a callback function for each processing step and/or a callback for * when processing is finished; you would do that by defining these functions * and passing their names into the batch setup function. * * Callback function signatures, like hook definitions, are described by * creating and documenting dummy functions in a *.api.php file; normally, the * dummy callback function's name should start with "callback_", and you should * document the parameters and return value and provide a sample function body. * Then your API documentation can refer to this callback function in its * documentation. A user of your API can usually name their callback function * anything they want, although a standard name would be to replace "callback_" * with the module name. * * @see hooks * @see themeable * * @} */ /** * @defgroup form_api Form generation * @{ * Describes how to generate and manipulate forms and process form submissions. * * Drupal provides a Form API in order to achieve consistency in its form * processing and presentation, while simplifying code and reducing the amount * of HTML that must be explicitly generated by a module. * * @section generating_forms Creating forms * Forms are defined as classes that implement the * \Drupal\Core\Form\FormInterface and are built using the * \Drupal\Core\Form\FormBuilder class. Drupal provides a couple of utility * classes that can be extended as a starting point for most basic forms, the * most commonly used of which is \Drupal\Core\Form\FormBase. FormBuilder * handles the low level processing of forms such as rendering the necessary * HTML, initial processing of incoming$_POST data, and delegating to your * implementation of FormInterface for validation and processing of submitted * data. * * Here is an example of a Form class: * @code * namespace Drupal\mymodule\Form; * * use Drupal\Core\Form\FormBase;