(Vous pouvez retrouver cet article en 🇫🇷 ici)
In this article, I’ll show you 10 tips that can improve your PHP code 🔍 🐘
In order to make this article easier to read, I’ll write some pieces of code that I’ve encountered and introduce a commented solution if needed, as you know there are 4242424242424 ways to do the same thing ✨ and It’s OK to disagree with my solution 😅
👀 For my examples I use PHP 7.4
3,2,1… let’s start 🏁 🔥
1- In this use case, just return the expression 👌
2- Null coalescing operator for the win 😍
💡It’s very handy to avoid exceptions when you want to access a key that doesn’t exist
3- 🛑 Avoid
method_exist if possible and favors interfaces
In this example, the big advantage of the interface is that we avoid typographical errors and we have the advantages of the IDE (search, autocomplete …).
In addition, the statement
if method_exists($user, 'setUpdatedAt')is strongly linked to the name of the method, with an interface we can rename the method in a safe way and as it’s an interface the method
setUpdateAt can be in a trait and be reused without logic duplication.
4 - Make the code expressive 🗣
In the example, we could even extract the statement in a dedicated method
isLoggable, which reduces the cognitive impact and we, immediately understand that the manipulated object is loggable.
5 - Straight to the point 🥅
6- Initialize your helper once 😛
7- Unpack an array 🎩
In the same way, we can also assign variables from an array, it is useful if a function returns an array 🚀
8 - Avoid using
This function is too “generic”, use it can hide some potentials bugs, you can refer to this article for more explanation.
9 - Use array keys as discriminator 📚
In some cases, it’s very handy to use the keys of an array as a discriminator in order to find the desired value. Let’s imagine that we have a function that says “hello” in different languages, the 1st reflex would be to make a basic
The main drawback is that as we add translations, the switch case will grow, and above all, we have to modify this method which violates the “O” of SOLID 😬
A good alternative is to “configure” the available translations in an
array like this:
We can go more further and make our code more robust by avoiding throwing an exception with a “Value Object”, something like:
This solution requires a little more code but it’s more robust 💪 and cleaner 🧼, we can reuse the
Locale object and if we have a locale that is not managed, the application will crash upstream, therefore, quicker than in the sayHello method and it’s important to fail fast in the case of an error 💡
var_dump accept several parameters 😄
unset($user, $product) and
var_dump($data, 42, $users) are valid code.
That’s all for these 10 tips, there are more and I’ll probably write more articles in this way, follow me to not miss my next posts.
Thanks for reading, don’t forget to share and applause 👏