Generaly, using DocBlock in PHP is one of the best practices. It was very usefull for previous versions of PHP (lesser then PHP 7.3 or especially 7.4). It informs developers about class properties types, arguments types expected and values returned by methods (in case of lack of strict typying in PHP).
Lets say in PHP 5.6, code can look like:
namespace App\Service\Catalog\Category;
use App\Entity\Catalog\Category\Category;
use App\Repository\Catalog\Category\CategoryRepository;
class CategoryService
{
/** @var CategoryRepository */
private $categoryRepository;
/** @var int */
private $currentNestingLevel = 1;
/**
* CategoryService constructor.
* @param CategoryRepository $categoryRepository
*/
public function __construct(Category $categoryRepository)
{
$this->categoryRepository = $categoryRepository;
}
/**
* @param $parentCategoryId
* @return array
*/
public function getCategoriesDataByParentCategoryId($parentCategoryId)
{
$categories = $this->categoryRepository->getByParentCategoryId($parentCategoryId);
$categoriesData = [];
foreach ($categories as $category) {
$categoriesData[] = $this->getCategoryData($category);
}
return $categoriesData;
}
}
But these DocBlocks do not provide any additional information in this case, when we use PHP 7.4:
namespace App\Service\Catalog\Category;
use App\Repository\Catalog\Category\CategoryRepository;
class CategoryService
{
private CategoryRepository $categoryRepository;
private int $currentNestingLevel = 1;
public function __construct(CategoryRepository $categoryRepository)
{
$this->categoryRepository = $categoryRepository;
}
public function getCategoriesDataByParentCategoryId(int $parentCategoryId): array
{
$categories = $this->categoryRepository->getByParentCategoryId($parentCategoryId);
$categoriesData = [];
foreach ($categories as $category) {
$categoriesData[] = $this->getCategoryData($category);
}
return $categoriesData;
}
}
Robert C. Martin writes in Clean code, that using JavaDoc(sic!) for all methods/variables, etc. is bad practices and decreases code readability. Additionaly, he said it is possible, that comment (DocBlock) does not reflect current state of specified element (e.g. in DocBlock we have int, but variable was changed into string)
As I checked, PSR standards mainly said only, how to use DocBlock and how they should look like, but not when they should be used.
What do you think about this? Should we use DocBlock always for all elements in code or only in specific cases? What kind of pros and cons you see in both cases?