PHP โครงสร้างโปรเจกต์และแนวปฏิบัติที่ดี



บทนี้รวบทุกอย่างที่เรียนมาเป็น “โครงร่าง” ที่ใช้เริ่มโปรเจกต์จริงได้ และเป็นฐานของ 4 โปรเจกต์ในเฟสถัดไป

โครงสร้างโฟลเดอร์

my-app/
├── public/              ← webroot — เว็บเซิร์ฟเวอร์ชี้มาที่นี่เท่านั้น
│   ├── index.php         ← front controller (จุดเข้าเดียว)
│   └── assets/           ← css, js, รูป
├── src/                  ← โค้ดของแอป (namespace App\)
│   ├── Http/             ← controller, middleware, router
│   ├── Domain/           ← logic ธุรกิจ (Order, Product, ...)
│   └── Support/          ← helper
├── config/
│   └── app.php
├── templates/            ← ไฟล์ view (.php)
├── storage/              ← ไฟล์ที่เขียนตอนรัน (uploads, logs, cache) — ไม่ commit
│   ├── logs/
│   └── uploads/
├── tests/               ← เทสต์ (namespace Tests\)
├── vendor/              ← Composer — ไม่ commit
├── .env                 ← ความลับ — ไม่ commit
├── .env.example
├── .gitignore
├── composer.json
├── composer.lock
├── phpunit.xml
└── phpstan.dist.neon

หลักสำคัญ: เว็บเซิร์ฟเวอร์ชี้ document root ไปที่ public/ เท่านั้น — src/, .env, config/, vendor/ อยู่นอก webroot เข้าถึงจากเบราว์เซอร์ตรง ๆ ไม่ได้

composer.json

{
    "name": "pepder/my-app",
    "require": {
        "php": ">=8.3",
        "vlucas/phpdotenv": "^5.6"
    },
    "require-dev": {
        "phpunit/phpunit": "^11.4",
        "phpstan/phpstan": "^2.0",
        "friendsofphp/php-cs-fixer": "^3.64"
    },
    "autoload": {
        "psr-4": { "App\\": "src/" }
    },
    "autoload-dev": {
        "psr-4": { "Tests\\": "tests/" }
    },
    "scripts": {
        "test": "phpunit",
        "stan": "phpstan analyse",
        "cs": "php-cs-fixer fix",
        "check": ["@cs", "@stan", "@test"]
    }
}

.gitignore

/vendor/
/.env
/storage/logs/*
/storage/uploads/*
!/storage/logs/.gitkeep
!/storage/uploads/.gitkeep
.phpunit.cache/
.php-cs-fixer.cache

front controller — public/index.php

ทุกคำขอเข้าไฟล์เดียว แล้ว router ตัดสินว่าเรียกอะไร:

<?php
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

// 1. โหลด environment
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->safeLoad();

$config = require __DIR__ . '/../config/app.php';

// 2. error handling ตาม environment
if ($config['debug']) {
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
} else {
    ini_set('display_errors', '0');
    ini_set('log_errors', '1');
    ini_set('error_log', __DIR__ . '/../storage/logs/php.log');
}

set_exception_handler(function (\Throwable $e) use ($config): void {
    error_log((string) $e);
    http_response_code(500);
    if ($config['debug']) {
        echo '<pre>' . htmlspecialchars((string) $e) . '</pre>';
    } else {
        echo 'เกิดข้อผิดพลาด กรุณาลองใหม่ภายหลัง';
    }
});

// 3. bootstrap บริการ
session_start();
$pdo = new PDO(
    $config['db']['dsn'],
    $config['db']['user'],
    $config['db']['pass'],
    [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ],
);

// 4. routing
$router = new App\Http\Router();

$router->get('/', [App\Http\HomeController::class, 'index']);
$router->get('/posts/{id}', [App\Http\PostController::class, 'show']);
$router->post('/posts', [App\Http\PostController::class, 'store']);

$router->dispatch(
    $_SERVER['REQUEST_METHOD'],
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH),
    ['pdo' => $pdo, 'config' => $config],
);

router อย่างง่าย

<?php
declare(strict_types=1);

namespace App\Http;

final class Router
{
    /** @var array<array{method:string, pattern:string, handler:callable|array}> */
    private array $routes = [];

    public function get(string $path, callable|array $handler): void
    {
        $this->routes[] = ['method' => 'GET', 'pattern' => $this->compile($path), 'handler' => $handler];
    }

    public function post(string $path, callable|array $handler): void
    {
        $this->routes[] = ['method' => 'POST', 'pattern' => $this->compile($path), 'handler' => $handler];
    }

    private function compile(string $path): string
    {
        // /posts/{id} -> #^/posts/(?<id>[^/]+)$#
        $regex = preg_replace('#\{(\w+)\}#', '(?<$1>[^/]+)', $path);
        return "#^$regex$#";
    }

    public function dispatch(string $method, string $path, array $deps): void
    {
        foreach ($this->routes as $route) {
            if ($route['method'] !== $method) {
                continue;
            }
            if (preg_match($route['pattern'], $path, $m)) {
                $params = array_filter($m, 'is_string', ARRAY_FILTER_USE_KEY);

                $handler = $route['handler'];
                if (is_array($handler)) {
                    [$class, $action] = $handler;
                    $handler = [new $class($deps), $action];
                }
                echo $handler($params);
                return;
            }
        }

        http_response_code(404);
        echo 'ไม่พบหน้าที่ต้องการ';
    }
}

ตั้งค่าเว็บเซิร์ฟเวอร์

dev:

php -S localhost:8000 -t public

Nginx (production):

server {
    root /var/www/my-app/public;      # ชี้ที่ public/ เท่านั้น
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known) { deny all; }   # กัน .env, .git
}

best practices สรุปทั้งซีรีส์

ภาษา

  • declare(strict_types=1); ทุกไฟล์
  • ประกาศ type ทุก parameter, return, property
  • === / !== เสมอ, match แทน switch
  • enum แทน magic string

โครงสร้าง

  • 1 ไฟล์ 1 คลาส, ชื่อไฟล์ = ชื่อคลาส, PSR-4
  • private เป็นค่าเริ่มต้น เปิดเมื่อจำเป็น
  • composition มากกว่า inheritance
  • คลาสรับ dependency ทาง constructor (ไม่ new ข้างใน, ไม่ global)

ความปลอดภัย

  • prepared statement ทุก query ที่มีตัวแปร
  • htmlspecialchars(ENT_QUOTES, 'UTF-8') ทุกค่าที่แสดง
  • password_hash / password_verify เท่านั้น
  • CSRF token ทุกฟอร์มที่เปลี่ยนข้อมูล
  • validate ตอนรับ, escape ตอนแสดง — อย่าเชื่อ input
  • secret ใน .env ไม่ commit

คุณภาพ

  • Composer + composer.lock commit
  • PHPUnit + PHPStan (level 6+) + CS-Fixer ใน composer check
  • error: dev แสดง / production log
  • DateTimeImmutable, mb_* กับข้อความ, __DIR__ กับ path

เรื่องที่คนมักพลาด

  • document root ชี้ที่รากโปรเจกต์ ไม่ใช่ public/ — /.env, /config/app.php, /vendor/ ดาวน์โหลดได้
  • หลายจุดเข้า (login.php, dashboard.php, …) กระจายทั้งโปรเจกต์ — จัดการ auth/config ซ้ำทุกไฟล์ ใช้ front controller
  • storage/ ถูก commit หรือไม่มีสิทธิ์เขียน — logs/uploads เขียนไม่ได้
  • ไม่มี .gitkeep ใน storage ที่ ignore ไฟล์ข้างใน — clone มาแล้วโฟลเดอร์หาย
  • ผสม logic ธุรกิจใน controller / ในไฟล์ view — แยก Domain/ ออกมา ทดสอบได้
  • สร้างโครงใหญ่เกินตั้งแต่วันแรก — เริ่มเล็ก (src/ แบน ๆ) แล้วแตกโฟลเดอร์เมื่อโตพอ

สรุป

  • webroot = public/ เท่านั้น, ทุกอย่างอื่นอยู่นอก
  • public/index.php เป็น front controller: โหลด env → ตั้ง error handler → bootstrap (session, PDO) → router → dispatch
  • PSR-4 App\ → src/, Tests\ → tests/; commit composer.lock, ignore vendor/ .env storage/*
  • Nginx ชี้ root ที่ public/, try_files ... /index.php, deny dotfiles
  • best practices: strict types + type ทุกที่, prepared statement, escape output, password_hash, CSRF, secret ใน env, test+stan+cs

บทถัดไปเริ่มโปรเจกต์แรก — REST API สมุดโน้ต ที่ใช้ router, PDO, JSON และ validation ทั้งหมดที่เรียนมา