DEV Community

Simc Dev
Simc Dev

Posted on • Originally published at

4 Tips to Write Perfect PHP Code

1. Code to interfaces, not implementations

Interfaces are an indispensable element of well-designed code, although they seem unnecessary for novice programmers.

When designing an application, an interface allows you to focus on the necessary functionality without going into details.

Initially, I did not use them because I did not see any use for them. Only relatively recently have I appreciated their gravity in the systems I design.

The most significant advantage of interfaces is the contract they define. As long as you rely solely on the interface (and don’t mention the implementing classes in any way), you can change the implementation details without affecting your application.

2. Avoid inheritance
This principle is directly related to the recommendation to use the interfaces I described above.

Inheriting and using abstract classes may seem tempting. We are naturally fit to find and apply patterns. We try to create shortcuts to temporarily facilitate our work.

However, I know from experience that it ends in problems later on. This is known as technological debt.

3. Type hint variables
Do you use doc-blocks to hint to the IDE about the variable type? If not, I recommend getting started. PHP is an interpretable language, the variable type may change during code execution.

While the PHP engine may not have problems with the code being executed, your code editor may not know what data the variable contains. Is it a User class object? Or maybe “false” or “null”.

With this knowledge, your IDE can help you catch simple errors that can happen frequently.

4. Adopt Command-Query Separation
This principle, coined by Bertrand Meyer, is beneficial for building class functions (or methods) or API endpoints.

Bertrand recommends that the function you create is always a command or a query, but never a command and a query at the same time.

A command is a function that modifies the state in any way (i.e. deleteUser, removeFile, sendEmail), while the query is a function that returns anything (i.e. findUser, getOwner, findAll, findOneBy).

Top comments (2)

milanobrtlik profile image
Milan Obrtlik

What is perfect code?

moopet profile image
Ben Sinclair

Compiler don't warn me, don't warn me, no more.