PHP Best Practices and Project Structure
# Chapter 29: PHP Best Practices and Project Structure
1. Introduction
Welcome to Chapter 29! You have learned the syntax, the functions, the databases, the security protocols, and the architecture. But knowing *how* to write code is only half the battle. Knowing how to write *Clean Code* is what makes a professional developer. Clean code is readable, maintainable, and predictable. In this penultimate chapter, we will discuss industry-standard best practices, how to structure your folders, the DRY principle, and the PSR coding standards.2. Learning Objectives
By the end of this chapter, you will be able to:- Understand the DRY (Don't Repeat Yourself) principle.
- Structure a PHP project directory professionally.
- Write readable, self-documenting code.
-
Understand the importance of the
.envfile for configurations.
- Familiarize yourself with PHP-FIG and PSR standards.
3. The DRY Principle
Don't Repeat Yourself (DRY). If you find yourself copying and pasting the exact same block of code into three different files, you are violating the DRY principle. Instead, wrap that code in a Function, a Class, or put it in aninclude file.
*Why?* If you find a bug in that code later, you only have to fix it in ONE place, rather than tracking down the 20 places you pasted it.
4. Professional Folder Structure
A professional PHP application is not just 50.php files dumped into the main htdocs folder. It should be highly organized.
Example Structure:
5. The .env File (Environment Variables)
Never hardcode your database passwords into your PHP files. Instead, use an Environment Variable file (.env). This file sits at the root of your project and is NEVER uploaded to public repositories like GitHub.
.env
Using libraries like vlucas/phpdotenv, PHP reads this file securely, allowing your code to look like this:
6. Self-Documenting Code
Code is read 10 times more often than it is written. Write your code so that a human can understand it immediately.Bad (Unclear):
Good (Self-Documenting):
*Notice how the "Good" code barely needs comments. The variable and function names explain exactly what is happening.*
7. PSR Standards
The PHP Framework Interop Group (PHP-FIG) created the PSR (PHP Standard Recommendations). It is a set of rules all professional PHP developers agree to follow so everyone's code looks uniform.-
PSR-1 & PSR-12 (Coding Style): Rules like using
<?php(no short tags), using CamelCase for methods, PascalCase for Classes, and indenting with 4 spaces.
-
PSR-4 (Autoloading): A standard that allows PHP to automatically find and
requireyour Classes based on your folder structure, so you never have to writerequire 'Model.php';manually again.
8. Real-World Examples
In professional environments, developers use Composer, the PHP dependency manager. If you need to manipulate images, you don't write 1,000 lines of complex math from scratch. You runcomposer require intervention/image, and Composer automatically downloads the library into your /vendor folder, fully compliant with PSR-4, ready for you to use instantly.
9. Output Explanations
By moving all your PHP logic into a/src folder, and only putting index.php in the /public folder (and pointing your web server's document root to /public), you create a massive security wall. Even if your web server misconfigures and accidentally shows raw PHP files as plain text, hackers can only see index.php. All your sensitive Models, Controllers, and .env passwords are physically located *outside* the public web root, rendering them impossible to access via a browser.
10. Common Mistakes
-
Magic Numbers: Using
if ($status == 4)in your code. What does 4 mean? Use constants or clear variables:if ($status == STATUSBANNED).
-
Leaving test code: Leaving
vardump($_POST); die();in your live code.
- Not using Source Control: Building a massive project without using Git and GitHub. If you delete a file by accident without Git, it is gone forever.
11. Best Practices
- KISS (Keep It Simple, Stupid): Don't write a highly complex, confusing one-line block of code just to show off. Simple, readable code is always better.
- Validate incoming data immediately. Escape outgoing data at the very last possible second before it hits the HTML.
12. Exercises
- 1. Look at the code you wrote for Chapter 22 (CRUD). Are your variable names descriptive? Are your database credentials hardcoded?
-
2.
Refactor a script by moving the database connection logic into a separate
config.phpfile and including it.
13. Mini Project: Refactoring Legacy Code
Task: Take a messy, procedural block of code and refactor it into clean, documented code.Legacy Spaghetti:
Refactored Clean Code:
14. Coding Challenges
Challenge 1: Create a proper directory structure on your local machine mimicking the one in Section 4. Create dummy files inside them to get a feel for a real project workspace.15. MCQs with Answers
1. What does the DRY principle stand for? A) Do Repeat Yourself B) Data Routing Yield C) Don't Repeat Yourself D) Database Response Yield *Answer: C*2. Why should database credentials be placed in a .env file instead of directly in the PHP script?
A) Because .env files execute faster.
B) To keep secrets out of version control (like GitHub) and separate configurations from application logic.
C) Because PHP requires it.
D) To make the database run faster.
*Answer: B*
3. What is Composer used for in PHP? A) Writing CSS. B) Managing dependencies and third-party libraries. C) Designing databases. D) Hosting websites. *Answer: B*
16. Interview Questions
Q: Explain the benefit of pointing the Web Server's document root to a/public folder rather than the project root.
*A:* Security. If the document root is /public, browsers can only access files inside that specific folder (index.php, CSS, JS). All sensitive application code, vendor libraries, and .env files reside in the parent directory, physically inaccessible from the web, preventing accidental source code or password leakage.
Q: What are PSR standards? *A:* PHP Standard Recommendations (PSR) are a set of guidelines published by the PHP-FIG. They standardize coding styles (PSR-12) and autoloading (PSR-4), ensuring that code written by different developers or frameworks remains consistent, interoperable, and highly readable across the global PHP ecosystem.
17. FAQs
Q: Where can I learn more about Composer and Frameworks? *A:* Visitgetcomposer.org. Once you are comfortable with pure PHP, you should immediately look into "Laravel" (laravel.com), the most popular PHP framework in the world, which utilizes all the best practices discussed in this chapter out of the box.