Edit in GitHubLog an issue

DocBlock standard

This standard defines the requirements and conventions for adding inline code documentation, known as DocBlocks.

Some parts of the code might not comply with this standard, but we are working to improve this.

Following these standards is optional for third-party developers, but doing so helps to create consistent, clean, and easy to read inline documentation.

Use RFC 2119 to interpret the "MUST," "MUST NOT," "REQUIRED," "SHALL," "SHALL NOT," "SHOULD," "SHOULD NOT," "RECOMMENDED," "MAY," and "OPTIONAL keywords."

Scope of the standard#

The goal of this standard is to unify usage of code DocBlocks for all files, not specific to a particular language.

The following is assumed by default:

  • Formatting according to the phpDocumentor standard
  • Requirements apply for all files regardless of programming language, but a DocBlock standard for the particular language may override it.

General principles#

The documentation should follow two simple principles:

  1. Be as short as possible.
  2. Include all necessary information without duplication.

Short documentation#

The documentation should be as short as possible, while including all necessary details.

Below are ways of improving code to help simplify documentation:

  • Make code self-explanatory.
  • Put all possible information in the names of classes, methods, and variables. (e.g. use $timeInSec instead of $time)
  • Break down a method into smaller methods with descriptive names. For example:
Copied to your clipboard
1 public function getPrice()
2 {
3 $price = 0;
4 $price += $this->getBasePrice();
5 $price -= $this->getDiscount();
6 return $price;
7 }
8
9 private function getBasePrice()
10 {
11 // calculate base price
12 }
13
14 private function getDiscount()
15 {
16 if (it is discount time) {
17 return 10;
18 }
19
20 return 0;
21 }

Include all necessary details#

  1. Identify the details a developer needs to work with your code.

  2. Ignore the implementation details (i.e. private methods/properties and method bodies) and focus on what the public interface signature provides. If possible, improve the interface to provide more information.

  3. Add any remaining information that a developer may need to the DocBlock.

Files#

Each source code file must have a DocBlock header with a short description of the file. After the short description, there can be a long description.

Both short and long descriptions (for file headers and herein) must be separated from other elements using one empty line (implied empty line in terms of DocBlock syntax, where any line within DocBlock starts from *.

If the description or short description happens to be the first one after the DocBlock opening tag (/**) or last one before the closing tag (*/), it should not be separated with an empty line.

DocBlock Header in a PHP-file:

Copied to your clipboard
1/**
2 * Short description...
3 *
4 * Long description
5 * Broken down into several lines
6 *
7 * License notice...
8 */

DocBlock Header in an XML-file:

Copied to your clipboard
1<!--
2/**
3 * Short description...
4 *
5 * Long description
6 * Broken down into several lines
7 *
8 * License notice...
9 */
10-->

License Notice and Copyright#

Any file in the source should have a header with license and copyright notice. Exceptions are files with formats that do not support commenting.

License notice and copyright MUST be declared at the very beginning of the file. If the file contains a structural element (for example, a class), the description for the element should be declared as a separate DocBlock.

Use the following templates for the license notice and copyright blocks:

Template for PHP files:

Copied to your clipboard
1<?php
2/**
3 * Copyright © Magento, Inc. All rights reserved.
4 * See COPYING.txt for license details.
5 */
6
7namespace Magento\Framework\Api;
8
9/**
10 * Provides metadata about an attribute.
11 *
12 * @api
13 */
14interface MetadataObjectInterface
15{
16 ...
17}

Template for XML Files:

Copied to your clipboard
1<?xml version="1.0"?>
2<!--
3/**
4 * Copyright © Magento, Inc. All rights reserved.
5 * See COPYING.txt for license details.
6 */
7-->

Template for JS Files:

Copied to your clipboard
1/**
2 * Copyright © Magento, Inc. All rights reserved.
3 * See COPYING.txt for license details.
4 */

Code structural elements#

A structural element is defined in phpDocumentor as part of the imperative source code, such as PHP or JavaScript, or procedural SQL. For example:

  • namespace
  • class
  • interface
  • function
  • property
  • method

If the source code file has one and only one standalone structural element, as may be required by language-specific coding standard, the file DocBlock is to be reused for this element.

Therefore, classes that are declared in dedicated files must have either no DocBlock or exactly one DocBlock, which refers to the class and file at the same time.

DocBlock for a Class:

Copied to your clipboard
1/**
2 * Autoloader with class map capability
3 *
4 * ...
5 */
6class Autoload
7{

While declaring classes or functions, if there must be another file with source code included, the inclusion construct must not be before file header and it must not separate the element DocBlock from the element. There are two solutions possible:

  • Have the file header DocBlock separately, then inclusion construct, then a DocBlock for the element with duplicated short description.
  • Include it after declaring the element (it is possible in PHP and will not cause issues before execution).

DocBlock with Included Script File:

Copied to your clipboard
1<?php
2/**
3 * Copyright © Magento, Inc. All rights reserved.
4 * See COPYING.txt for license details.
5 */
6
7/**
8 * Magento integration Magento test framework (MTF) bootstrap
9 *
10 * ...
11 */
12
13require __DIR__ . '/../bootstrap.php';
14
15namespace Magento\Test;
16
17/**
18 * Magento integration Magento test framework (MTF) bootstrap
19 */
20class Bootstrap
21{

DocBlock with Included Class File:

Copied to your clipboard
1<?php
2/**
3 * Copyright © Magento, Inc. All rights reserved.
4 * See COPYING.txt for license details.
5 */
6
7namespace Magento\Framework\Profiler\Adapter;
8
9use Magento\Framework\Profiler\AdapterAbstract;
10
11/**
12 * Profiler CSV adapter
13 *
14 * ...
15 */
16class Csv extends AdapterAbstract
17{
18// ...
19 public function setFile($file)
20 {
21 if (!isValidFile($file)) {
22 throw new \ArgumentException('A valid file name is expected.');
23 }
24 // ...
25 }
26}
27
28require_once __DIR__ . '/../../functions.php';

Classes and interfaces#

Classes and interfaces should have a short description with a human-readable description of the class. If the short description adds no additional information beyond what the type name already supplies, the short description must be omitted.

Good:

Handler for PHP errors/warnings/notices that converts them to exceptions. class ErrorHandler { ... }

Bad:

Error Handler class ErrorHandler { ... }

If possible, add use cases which suggests where developers can or cannot use the class.

Short name form#

It is encouraged to use the short form of the name to encourage readability and consistency with the type hint. The only exception is in the Service/DTO classes due to tooling requirements.

Example of a Method DocBlock:

Copied to your clipboard
1use Magento\Logger;
2use Magento\Math\Random;
3use Magento\Stdlib\DateTime as StdlibDateTime;
4
5/**
6 * @var Logger
7 */
8private $logger;
9
10/**
11 * Description of method here.
12 *
13 * @param Random $mathRandom
14 * @param StdlibDateTime $dateTime
15 * @param int $number
16 */
17private function doSomething(Random $mathRandom, StdlibDateTime $dateTime, $number)
18{
19
20}

Class attributes#

Class attributes must have a type declaration using @var tag.

Example of Class Attribute:

Copied to your clipboard
1<?php
2/**
3 * Copyright © Magento, Inc. All rights reserved.
4 * See COPYING.txt for license details.
5 */
6
7namespace Magento;
8
9class Profiler
10{
11 /**
12 * @var Profiler
13 */
14 protected static $instance = null;

Functions and methods#

In general, a typed method signature must be preferred over PHPDoc annotations whenever possible.

Functions and methods should have:

  • A short description that adds meaningful information beyond the method name.

  • If the purpose of the method is not obvious, a long description that explains the motivation behind the implementation. The comment must describe why method is implemented and not how. For example:

    • If a workaround or hack is implemented, explain why it is necessary and include any other details necessary to understand the algorithm.
    • For non-obvious implementations where the implementation logic is complicated or does not correspond to the Technical Vision or other known best practices, include an explanation in the doc block's description. An implementation is non-obvious if another developer has questions about it.
  • The declaration of all arguments (if any) using the @param tag, unless the argument type is indicated in the method signature.

    All @param annotations must include the appropriate argument type. If any argument requires a @param annotation, all arguments must be listed (all or none). @param annotations must be in the same order as the method arguments.

  • The declaration of the return type using the @return tag must only be added if the method return type signature does not supply all necessary information (see below for more information on return types).

  • A declaration of possible exceptions using the @throws tag, if the actual body of function triggers an exception. All occurrences of @throws in a DocBlock must be after @param and @return annotations.

Exceptions to these rules:

  • Testing methods in Unit tests may have doc blocks to describe the purpose of the test, such as referencing Github issues.
  • Test method annotations may include data providers and other testing annotations.

Things to include#

  • An explanation of input arguments and return values if it is not obvious from their name and type.

    This is applicable in the following cases:

    • There is more than one possible input/output type.

      For example: @return Config|null. The DocBlock should explain what situations will return null.

      Another example: @param FileInterface|null. The DocBlock should explain what happens when the value of the parameter is null.

      Ideally, implementations such as these should be avoided:

    • The input/output type is a simple type and the format is not clear from the name.

    • The input/output is an array with a specific structure.

  • The intent of the method along with when or where it can be used.

  • If an exception is thrown by a method, explain the cause or situation.

  • If the input is confusing or complicated, add examples of the method's usage in client code or examples of the argument.

Things to avoid#

  • Copying the algorithm. The algorithm must be self-explanatory and understood by reviewing the code and unit tests.
  • Information that is out of date or has the potential to become out of date.

Example of a Method DocBlock:

Copied to your clipboard
1/**
2 * Merge the config XML files
3 *
4 * @param array $configFiles
5 * @return void
6 * @throws \Magento\Exception if a non-existing or invalid XML file passed
7 */
8protected function merge($configFiles)
9{
10 $domConfig = new \Magento\Config\Dom($this->_getInitialXml(), $this->_getIdAttributes());
11 foreach ($configFiles as $file) {
12 if (!file_exists($file)) {
13 throw new \Magento\Exception("File does not exist: {$file}");
14 }
15 $domConfig->merge(file_get_contents($file));
16 if (!$domConfig->validate($this->getSchemaFile(), $errors)) {
17 $message = "Invalid XML file: {$file}\n";
18 /** @var libXMLError $error */
19 foreach ($errors as $error) {
20 $message .= "{$error->message} Line: {$error->line}\n";
21 }
22 throw new \Magento\Exception($message);
23 }
24 }
25 $this->_dom = $domConfig->getDom();
26}

Divergence in @throws tag#

In general, use the @throws tag when the code uses throw:

Example of Throwing Exception Explicitly:

Copied to your clipboard
1/**
2 * Set an arbitrary value to specified element
3 *
4 * @param string $elementId
5 * @param string $attribute
6 * @param int|string|float|bool|object|null $value
7 * @return self
8 * @throws \InvalidArgumentException
9 */
10public function setAttribute($elementId, $attribute, $value)
11{
12 $this->_assertElementExists($elementId);
13 switch ($attribute) {
14 case self::PARENT: // break is intentionally omitted
15 case self::CHILDREN:
16 case self::GROUPS:
17 throw new \InvalidArgumentException("Attribute '{$attribute}' is reserved and cannot be set.");
18 break;
19 default:
20 $this->_elements[$elementId][$attribute] = $value;
21 break;
22 }
23 return $this;
24}

In this case, if an exception is thrown in a sub-routine, then @throws must not be used in the parent method.

However, if the only purpose of the referred sub-routine is to throw a specific exception – then @throws must be used in the parent method. For example:

Throwing Exception Implicitly:

Copied to your clipboard
1 /**
2 * Perform login process
3 *
4 * @param string $username
5 * @param string $password
6 * @return void
7 * @throws \Magento\Framework\Exception\AuthenticationException
8 */
9 public function login($username, $password)
10 {
11 if (empty($username) || empty($password)) {
12 self::throwException(
13 __(
14 'The account sign-in was incorrect or your account is disabled temporarily. '
15 . 'Please wait and try again later.'
16 )
17 );
18 }
19
20 try {
21 $this->_initCredentialStorage();
22 $this->getCredentialStorage()->login($username, $password);
23 if ($this->getCredentialStorage()->getId()) {
24 $this->getAuthStorage()->setUser($this->getCredentialStorage());
25 $this->getAuthStorage()->processLogin();
26
27 $this->_eventManager->dispatch(
28 'backend_auth_user_login_success',
29 ['user' => $this->getCredentialStorage()]
30 );
31 }
32
33 if (!$this->getAuthStorage()->getUser()) {
34 self::throwException(
35 __(
36 'The account sign-in was incorrect or your account is disabled temporarily. '
37 . 'Please wait and try again later.'
38 )
39 );
40 }
41 } catch (PluginAuthenticationException $e) {
42 $this->_eventManager->dispatch(
43 'backend_auth_user_login_failed',
44 ['user_name' => $username, 'exception' => $e]
45 );
46 throw $e;
47 } catch (\Magento\Framework\Exception\LocalizedException $e) {
48 $this->_eventManager->dispatch(
49 'backend_auth_user_login_failed',
50 ['user_name' => $username, 'exception' => $e]
51 );
52 self::throwException(
53 __(
54 $e->getMessage()? : 'The account sign-in was incorrect or your account is disabled temporarily. '
55 . 'Please wait and try again later.'
56 )
57 );
58 }
59 }

@return tag#

In general, method return type signatures should be prefered over @return type annotations. If that is not possible due to ambiguous return types or backward compatibility constraints, the @return type annotation must be used. If there is no explicit return statement in a method or function or a return statement without a value, a void return type must be declared in the method signature. For example:

Copied to your clipboard
1function setName(string $name): void
2{
3 $this->name = $name;
4}

If the method returns itself, the method signature return type must be self. Here is an example:

Copied to your clipboard
1function withField(string $fieldName): self
2{
3 $this->fields[] = $fieldName;
4 return $this;
5}

If for backward compatibility reasons, no return type can be added to the method signature, a @return $this annotation must be used.

Constants#

Constants may have a short description. If the short description adds no additional information beyond what the constant name already supplies, the short description must be omitted.

For example, a global constant:

Copied to your clipboard
1/**
2 * Directory separator shorthand, intended to make code more readable.
3 */
4define('DS', DIRECTORY_SEPARATOR);

Or constants in a class:

Copied to your clipboard
1class Profiler
2{
3 /**
4 * Separator literal to assemble timer identifier from timer names
5 */
6 const NESTING_SEPARATOR = '->';

DocBlock templates#

A DocBlock template is a DocBlock that starts from /**#@+*/ and ends with /**#@-*/. Templates are no longer supported by PHPDocumentor. Therefore, they MUST NOT be used.

It is encouraged to replace existing DocBlock templates with regular DocBlock comments when the file is being modified.

Structure of documentation space#

@author ,@category, @package, and @subpackage MUST NOT be used. Documentation is organized with the use of namespaces.

Other DocBlock tags#

@inheritdoc tag#

The @inheritdoc tag SHOULD NOT be used. If a child class method requires a long description to explain its purpose, it may use @inheritdoc to indicate the new description is intended as an addition to the parent method description. In general, such method overrides are a code smell and should be used as an incentive to make the code more self-documenting if possible.

DocBlock for the Interface:

Copied to your clipboard
1<?php
2/**
3 * Copyright © Magento, Inc. All rights reserved.
4 * See COPYING.txt for license details.
5 */
6
7/**
8 * Interface for mutable value object for integer values
9 */
10interface MutableInterface
11{
12 /**
13 * Returns 0, if no value is available
14 */
15 public function getVal(): int;
16
17 /**
18 * Sets 0 in case a non-integer value is passed
19 *
20 * @param int|string|bool|float|null $value
21 */
22 public function setVal($value): void;
23}

DocBlock for the implementation:

Copied to your clipboard
1<?php
2/**
3 * Copyright © Magento, Inc. All rights reserved.
4 * See COPYING.txt for license details.
5 */
6
7/**
8 * Limited mutable value object for integer values
9 */
10class LimitedMutableClass implements MutableInterface
11{
12 /**
13 * Returns integer value
14 */
15 public function getVal(): int
16 {
17 ...
18 }
19
20 /**
21 * Sets 0 in case a non-integer value is passed
22 *
23 * @param int|string|bool|float|null $value
24 */
25 public function setVal($value): void
26 {
27 ...
28 }
29}

@api tag#

The @api tag indicates the code is part of the public API and is subject to the Backward Compatibility Policy.

The @api tag can be applied to a constant, a method, or to the entire class/interface. If the @api tag is applied at the file level, then all methods within the file are part of the public API. You do not need to annotate each method individually.

See Semantic Versioning 2.0.0 for information about changing and updating code while maintaining backward compatibility.

@deprecated tag#

A deprecated class or method is one that has been superseded and may cease to exist in the future. It will be retained to provide backward compatibility until the next major component release.

Use the @deprecated tag to indicate that an element is to be deprecated.

You must explain why you added @deprecated tag. You MUST use the @see tag with references to the new implementation when code is deprecated and there is a new alternative.

For example:

Copied to your clipboard
1/**
2 * Get some object
3 *
4 * @deprecated Added to not break backward compatibility of the constructor signature
5 * by injecting the new dependency directly.
6 * The method can be removed in a future major release, when constructor signature can be changed
7 * @return SomeObjectInterface
8 */
9protected function getSomeObject()
10{
11 ...
12}
13
14/**
15 * Set price
16 *
17 * @deprecated Non-scoped price is not supported anymore
18 * @see setScopedPrice()
19 * @return void
20 */
21public function setPrice($price)
22{
23 ...
24}
25
26/**
27 * Set price for specified scope
28 *
29 * @return void
30 */
31public function setScopedPrice($price, $scopeType, $scopeId)
32{
33 ...
34}

@var inline tag#

For the purpose of automatic type hinting in an IDE, an inline notation of @var tag can be used wherever the IDE is unable to resolve variable type. This tag declares variables that will emerge in following lines of code:

Inline Type Hinting:

Copied to your clipboard
1/** @var libXMLError $error */
2foreach ($errors as $error) {

Some IDEs understand a different notation, where the type is specified after variable name. This notation is also valid:

Inline Type Hinting Variation:

Copied to your clipboard
1/** @var $error libXMLError */
2foreach ($errors as $error) {

@see tag#

Besides the normal way of using @see tags as recommended by phpDocumentor, it may be used as an addition to @var, when the @var is already used in this comment.

Specifically, this is possible when a PHP file is composed from multiple file includes. As a result, variables may contain objects of different types depending on context:

Copied to your clipboard
1/**
2 * @var $this ClassOne
3 * @see ClassTwo
4 * @see FooInterface
5 */

@method tag#

The @method allows a class to know which ‘magic’ methods are callable.

Syntax:

Copied to your clipboard
@method [[static] return type] [name]([[type] [parameter]<, ...>]) [<description>]

See PHP documentation for more information about the @method tag.

Copied to your clipboard
1<?php
2/**
3 * Copyright © Magento, Inc. All rights reserved.
4 * See COPYING.txt for license details.
5 */
6
7namespace Magento\Catalog\Model\Product;
8
9use Magento\Framework\Model\AbstractModel;
10
11/**
12 * Image operations
13 *
14 * @method string getFile()
15 * @method string getLabel()
16 * @method string getPosition()
17 */
18class Image extends AbstractModel
19{
20 //.....
21}

@link tag#

The @link tag indicates a custom relation between the associated Structural Elements and a website, identified by an absolute URI.

Syntax:

Copied to your clipboard
@link [URI] [<description>]

Other tags#

Any other valid DocBlock tags may be specified, if the author deems it necessary, but only if they bring valuable non-obvious information.

Formatting conventions#

Padding tags#

If there are two or more tags together in one DocBlock, their values may be padded, so that they could be visually aligned.

Copied to your clipboard
1/**
2 * ...
3 *
4 * @param string $argument
5 * @return bool
6 * @link http://example.com
7 */

Formatting consistency#

In a given DocBlock, the formatting style must be consistent.

For example, padding for visual alignment can be done in two ways:

Correct – align everything:

Copied to your clipboard
1/**
2 * ...
3 *
4 * @param string $parentId
5 * @param string $childId
6 * @param int|null $position
7 * @return int
8 * @see _insertChild() for position explanation
9 */

Also correct – do not align anything:

Copied to your clipboard
1/**
2 * ...
3 *
4 * @param string $parentId
5 * @param string $childId
6 * @param int|null $position
7 * @return int
8 * @see _insertChild() for position explanation
9 */
10public function reorderChild($parentId, $childId, $position)

Incorrect – align only partially:

Copied to your clipboard
1/**
2 * ...
3 *
4 * @param string $parentId
5 * @param string $childId
6 * @param int|null $position
7 * @return int
8 * @see _insertChild() for position explanation
9 */
  • Privacy
  • Terms of Use
  • Do not sell my personal information
  • AdChoices
Copyright © 2022 Adobe. All rights reserved.