Chapter 3: Coding Best Practices & Style
Introduction: Why Coding Standards Matter
Before we begin building the core components of our application, we must first establish a professional standard for how we write our code. In any long-term project, and especially when working in a team, a consistent and readable coding style is not a luxury—it's a requirement.
This chapter outlines the foundational best practices that we will adhere to throughout this book. We will cover the importance of community standards like PSR-12, how to properly document our code with DocBlocks, and other key principles like descriptive naming and the DRY principle. Adopting these practices from the outset is the key to creating a codebase that is clean, maintainable, and a pleasure to work with.
Adhering to PSR Standards
To ensure our code is consistent and interoperable with the wider PHP community, we adhere to the PHP Standards Recommendations (PSR). These are a set of guidelines published by the PHP Framework Interop Group (PHP-FIG), a body made up of representatives from many major PHP projects.
While there are many PSRs, two are fundamental to our development process:
- PSR-12 (Extended Coding Style): This standard provides a definitive set of rules for formatting PHP code. It covers everything from indentation (4 spaces, not tabs) and line length to the placement of curly braces and keywords. Following PSR-12 guarantees that all our code has a single, consistent, and professional appearance.
- PSR-4 (Autoloader): This standard defines a universal way to load classes from file paths. It specifies a direct mapping from a class's namespace to the directory structure. By adhering to PSR-4, the Composer autoloader can find and load any class in our application automatically.
Documenting Code with PHPDoc
Good code is not just about what it does, but how well it communicates its purpose. A DocBlock is a special type of comment that provides a formal, machine-readable description of a class, method, or property. We use the PHPDoc standard for writing these comments. A DocBlock begins with
/**
and ends with*/
, using special tags like@param
and@return
to describe the code's interface.<?php /** * A summary of what the method does. * * @param string $name The user's name. * @param int $age The user's age. * @return string A formatted greeting message. */ public function createGreeting(string $name, int $age): string { return "Hello, {$name}. You are {$age} years old."; }
Modern IDEs like PhpStorm can read these DocBlocks to provide better code completion and error checking, making your comments part of the application's interactive documentation.
Writing Effective Comments
While DocBlocks are for formal documentation, standard code comments are for providing context to the human reader. The most important rule for comments is to explain the "why," not the "what." Good code should explain what it is doing; comments should clarify the intent behind it.
Bad Comment (Redundant)
This type of comment is unhelpful because it adds no new information. It simply translates the PHP syntax
($i++)
into English ("Increment the counter"), creating noise that obscures the more important parts of the code.<?php // Increment the counter $i++;
Good Comment (Explains Intent)
This comment is valuable because it provides the missing business logic or context. It explains why we are incrementing the counter, which is a crucial piece of information for anyone maintaining this code in the future.
<?php // We need to skip the first record as it's a header row $i++;
Commenting in Smarty
Smarty has its own comment syntax: {* this is a Smarty comment... *}.
A key benefit of using Smarty comments is that they are completely removed during the template compilation process and never appear in the final HTML source code.
Descriptive Naming Conventions
Good code should be self-documenting, and the most important tool for this is using clear, descriptive names. A common myth is that shorter variable names are faster; in modern PHP, this is not true. The real cost of a project is developer time. Short, cryptic names like $pi or $res increase the "cognitive load," while a descriptive name like $pageInformation is instantly understandable. Our principle is simple: code is read far more often than it is written. Always optimise for the human.
Introduction: Why Coding Standards Matter
Before we begin building the core components of our application, we must first establish a professional standard for how we write our code. In any long-term project, and especially when working in a team, a consistent and readable coding style is not a luxury—it's a requirement.
This chapter outlines the foundational best practices that we will adhere to throughout this book. We will cover the importance of community standards like PSR-12, how to properly document our code with DocBlocks, and other key principles like descriptive naming and the DRY principle. Adopting these practices from the outset is the key to creating a codebase that is clean, maintainable, and a pleasure to work with.
Adhering to PSR Standards
To ensure our code is consistent and interoperable with the wider PHP community, we adhere to the PHP Standards Recommendations (PSR). These are a set of guidelines published by the PHP Framework Interop Group (PHP-FIG), a body made up of representatives from many major PHP projects.
While there are many PSRs, two are fundamental to our development process:
- PSR-12 (Extended Coding Style): This standard provides a definitive set of rules for formatting PHP code. It covers everything from indentation (4 spaces, not tabs) and line length to the placement of curly braces and keywords. Following PSR-12 guarantees that all our code has a single, consistent, and professional appearance.
- PSR-4 (Autoloader): This standard defines a universal way to load classes from file paths. It specifies a direct mapping from a class's namespace to the directory structure. By adhering to PSR-4, the Composer autoloader can find and load any class in our application automatically.
Self-Documenting Code
The ultimate goal of writing clean code is to make it self-documenting. This means using clear variable names and logical structures that make the code's purpose self-explanatory, requiring minimal comments.
Consider the following real-world example, which checks if a cache file is still valid.
Confusing Code (Before)
This version is technically correct, but the variable name $expired is confusing because it's true when the cache has not expired. A developer reading this has to pause and mentally decipher the inverted logic.
<?php $expired = (bool)(time() - filemtime($cacheFile) <= $maxAge); echo $cacheFile . ($expired ? ' is still valid' : ' has expired');
Self-Documenting Code (After)
By simply renaming the variable to $isCacheValid and using a standard if/else block, the code becomes instantly clear. There is no ambiguity and no need for comments; the code speaks for itself.
<?php $isCacheValid = (time() - filemtime($cacheFile)) <= $maxAge; if ($isCacheValid) { echo $cacheFile . ' is still valid.'; } else { echo $cacheFile . ' has expired.'; }
This also makes for A Clearer Ternary
This version is clean, still easy to understand, and a great example of a well-used ternary.
<?php // 1. The self-documenting variable name is the key. $isCacheValid = (time() - filemtime($cacheFile)) <= $maxAge; // 2. The ternary is now simple to read: "If the cache is valid, // set the message to 'is still valid', otherwise set it to 'has expired'." $statusMessage = $isCacheValid ? 'is still valid' : 'has expired'; // 3. The final output is clean. echo $cacheFile . ' ' . $statusMessage;
By using the self-documenting variable name, $isCacheValid, a ternary operator becomes clear and concise.
This is the standard we should always aim for: code that is so clear, its purpose is obvious without needing comments to explain it.
The DRY Principle (Don't Repeat Yourself)
The DRY principle states that every piece of knowledge or logic in a system should have a single, unambiguous, authoritative representation. In simpler terms: avoid duplicating code. When you find yourself copying and pasting code, abstract that logic into a reusable unit, such as a function or a class method.
Conclusion: The Foundation of Professional Code
The principles outlined in this chapter are the foundation of professional software development. By adopting this discipline from the outset, we ensure that any applications we build are not only powerful and functional but also a clean and stable base for future development.