#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.

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. > ``` 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. > ``` 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 ``` This version is clean, still easy to understand, and a great example of a well-used ternary. > ```php 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. ##Assigning Data to the View When passing data from your PHP model to your Smarty template, you have two main stylistic choices. > -Option 1: Multiple Assignments >This approach uses a separate assign() call for each piece of data. >PHP ```php assign('adList', $adList); $display->assign('totalCounts', $totalCounts); $display->assign('section', $section); ``` > -Option 2: Single Array Assignment >This approach gathers all the data into a single associative array and makes one assign() call. PHP ```php $adList, 'totalCounts' => $totalCounts, 'section' => $section ]; $display->assign($viewData); ``` ###Recommendation > While both methods are functionally identical and have no significant performance difference, we strongly recommend Option 1 (Multiple Assignments). This style is far more explicit and self-documenting. A developer can see at a glance exactly which variables are being passed to the template, which improves code readability and maintainability. ##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.

Shopping summary

Item

SubTotal: £

Empty Basket

this is a hidden panel

Completed in milliseconds

Completed in milliseconds

This is the top Panel

This is the bottom Panel