Documentation

PHPDoc Standards

Use PHPDoc to document all functions, methods, classes, and properties. Proper documentation improves code readability, IDE support, and team collaboration.

  • Document the purpose of each method or function.
  • List all parameters and their types.
  • Specify the return type and describe what is returned.

Example:

/**
 * Get the user's name.
 *
 * Retrieves the full name of a user by concatenating the first and last names.
 *
 * @param bool $capitalize Whether to capitalize the name or not. Defaults to true.
 * @return string The formatted full name of the user.
 */
public function getUserName(bool $capitalize = true): string
{
    $name = "{$this->firstName} {$this->lastName}";
    return $capitalize ? ucwords($name) : $name;
}
  • Use descriptive summaries and consistent formatting in all PHPDoc comments.

Inline Comments

Use inline comments to explain complex logic, decisions, or non-obvious code sections. Avoid redundant comments.

// Fetch the user from the database by their unique ID
$user = getUserFromDatabase($userId);

// If the user doesn't exist, throw an exception
if (!$user) {
    throw new Exception("User not found for ID: $userId");
}
  • Use comments to explain the "why" of the code, not the "what".
  • Keep comments up-to-date and relevant.

API Documentation

Use tools like Swagger (OpenAPI), Postman, Scramble, or API Blueprint to generate and maintain API documentation.

  • Use Swagger annotations in your code to describe API routes, parameters, and responses.
  • Ensure API documentation is always in sync with the implementation.
  • Use descriptive endpoints and request methods in your API design.

Example Using Swagger-PHP Annotations:

/**
 * @OA\Get(
 *     path="/users/{id}",
 *     summary="Get user details",
 *     description="Returns the details of a user by their ID.",
 *     @OA\Parameter(
 *         name="id",
 *         in="path",
 *         required=true,
 *         @OA\Schema(type="integer")
 *     ),
 *     @OA\Response(
 *         response=200,
 *         description="Successful operation",
 *         @OA\JsonContent(ref="#/components/schemas/User")
 *     ),
 *     @OA\Response(response=404, description="User not found"),
 * )
 */
public function getUser(int $id)
{
    // Get user details
    return response()->json($this->userRepository->findById($id));
}

Best Practices

  • Document all public methods, classes, and APIs.
  • Use automated tools to keep documentation up-to-date.
  • Review and update documentation as part of code reviews.
  • Provide examples and usage notes for complex APIs.