Every codebase tells a story. Some are page turners; others are crime scenes. After a decade of PHP I have collected a short list of habits that keep my projects in the first category.
1. Name things for what they do
processData() tells you nothing. normaliseInvoiceTotals() tells a future you everything.
2. Keep functions small
If a function needs a comment to explain its halves, it wants to be two functions.
3. Guard clauses over nesting
Return early. Deeply nested conditionals are where bugs hide.
function publish(Post $post): void
{
if (! $post->isReady()) {
return;
}
$post->publish();
}
4. Use typed properties
PHP 8 gives you types for free — use them everywhere. The compiler catches what code review might miss.
5. Prefer value objects
Passing around string for emails, slugs and currencies invites mix-ups. Small classes prevent them.
6. Validate at the boundary
Validate user input the moment it enters the system, then trust it internally.
7. Let the database do database work
Filtering in PHP after fetching everything is slower and more memory hungry than a WHERE clause.
8. Write the test you wish existed
One test for the bug you just fixed is worth ten abstract opinions about coverage.
9. Delete aggressively
Dead code is a liability. Version control remembers it so you do not have to.
10. Read the code you depend on
Ten minutes inside the framework source saves afternoons of guessing.
Clean code is not written, it is rewritten. Leave the campsite tidier than you found it.
0 Comments
No comments yet. Be the first to share your thoughts!
Leave a comment