5

PHP - Best Practices 2019

 3 years ago
source link: https://odan.github.io/2019/12/06/php-best-practice-2019.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Best Practices 2019

Daniel's Dev Blog

Developer, Trainer, Open Source Contributor

Blog About me Donate

PHP - Best Practices 2019

Daniel Opitz

Daniel Opitz

06 Dec 2019

I think it’s time for an fresh and simplified blog post about the latest PHP Best Practices in 2019 / 2020. A lot has changed within the last time I have written about this topic in 2018.

Principles and rules

Here are the most important rules:

  • KISS - Keep it simple, stupid
  • YAGNI - You Arent Gonna Need It
  • DRY - Don’t repeat yourself
  • SOLID - The First 5 Principles of Object Oriented Design
  • The Boy Scout Rule - Leave your code better than you found it

Coding styles

  • Code must follow PSR-1 and PSR-12. PSR-2 is deprecated.
  • Add full PSR-5 DocBlocks for all classes and all methods.

Naming

  • Use english names only (class names, method names, comments, variables names, database table and field names, etc…).
  • Use class suffixes / prefixes according to PSR Naming Conventions.
  • Follow industry best practices for your directory and file structure:

Common rules

  • All methods must have type declaration and return type declaration.
  • Methods without return statement must declared with void as their return type.
  • Class properties must have typed properties (PHP 7.4+).
  • Don’t mix data types for parameters and return types, except for nullable.
  • Don’t extend classes or create abstract classes for the sake of “code reuse”, except for traits with test code only.
  • Create final classes by default, except you have to mock it (e.g. repositories).
  • Create private methods by default. Don’t create protected methods.
  • All method parameters must be used.

Dependency injection

  • Use composition over inheritance.
  • Declare all class dependencies only within the constructor.
  • Don’t inject the container (PSR-11). The service locator is an anti-pattern.
  • A constructor can accept only dependencies as object.
  • Scalar data types (string, int, float, array) are not allowed for the constructor. Pass them as parameter object.

Tools

Use a static code analyzer to detect bugs and errors. For example:

Read more

© 2020 Daniel Opitz | Twitter


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK