Skip to main content
PHP for Beginners
CHAPTER 29 Beginner

PHP Best Practices and Project Structure

Updated: May 12, 2026
25 min read

# 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 .env file 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 an include 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:

text
12345678910111213
/my_project
├── /public            <-- The ONLY folder accessible by the browser
│   ├── index.php      <-- Central router
│   ├── /css
│   ├── /js
│   └── /images
├── /src               <-- Your backend code (Hidden from public)
│   ├── /Controllers
│   ├── /Models
│   └── /Views
├── /config            <-- Database connections
├── /vendor            <-- Third-party libraries (Composer)
└── .env               <-- Secret environment variables

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

env
123
DB_HOST=localhost
DB_USER=root
DB_PASS=mySecretPassword

Using libraries like vlucas/phpdotenv, PHP reads this file securely, allowing your code to look like this:

php
1
$pdo = new PDO("mysql:host=" . $_ENV[&#039;DB_HOST'], $_ENV['DB_USER'], $_ENV['DB_PASS']);

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):

php
12
$d = 5;
if ($d > 3) { doA(); }

Good (Self-Documenting):

php
123456
$user_failed_login_attempts = 5;
$max_allowed_attempts = 3;

if ($user_failed_login_attempts > $max_allowed_attempts) {
    lockUserAccount();
}

*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 require your Classes based on your folder structure, so you never have to write require '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 run composer 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. 1. Look at the code you wrote for Chapter 22 (CRUD). Are your variable names descriptive? Are your database credentials hardcoded?
  1. 2. Refactor a script by moving the database connection logic into a separate config.php file 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:

php
1234567891011
<?php
$e = $_POST[&#039;e'];
$p = $_POST[&#039;p'];
if($e != "" && $p != ""){
$db = new PDO("mysql:host=localhost;dbname=test", "root", "");
$s = $db->prepare("SELECT * FROM users WHERE email=:e");
$s->execute([&#039;:e'=>$e]);
$u = $s->fetch();
if($u && password_verify($p, $u[&#039;pass'])){
$_SESSION[&#039;user'] = $u['id']; echo "yes"; } else { echo "no"; } }
?>

Refactored Clean Code:

php
12345678910111213141516171819202122232425
<?php
session_start();
require_once &#039;config/database.php'; // DB connection hidden away

// 1. Clear variable names and early return
$email = trim($_POST[&#039;email'] ?? '');
$password = $_POST[&#039;password'] ?? '';

if (empty($email) || empty($password)) {
    die("Email and password are required.");
}

// 2. Clear query logic
$stmt = $pdo->prepare("SELECT id, password_hash FROM users WHERE email = :email");
$stmt->execute([&#039;:email' => $email]);
$user = $stmt->fetch();

// 3. Clear Authentication logic
if ($user && password_verify($password, $user[&#039;password_hash'])) {
    $_SESSION[&#039;user_id'] = $user['id'];
    echo "Login successful.";
} else {
    echo "Invalid credentials.";
}
?>

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:* Visit getcomposer.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.

18. Summary

You are now coding like a professional. You understand the absolute necessity of the DRY principle, self-documenting code, and strict security-minded folder structures. You have learned that clean code is a developer's best friend.

19. Next Chapter Recommendation

You have acquired all the tools, skills, and best practices. There is only one thing left to do. In Chapter 30: Final PHP Project, you will combine everything to build a complete, dynamic web application from scratch!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·