Tools
Log in
English

Learn to codePHP

PHP project structure

Based on PHP 8.3

Build a PHP project with public, src, tests and Composer PSR-4 as a zip.

Make a project skeleton

Choose what to build and how classes load (Composer or no Composer); the folder tree, file notes and layer picture follow. Click a file to see its starter code, then download the zip and run it.

Build a
Autoloading
Tests

Folder tree 11 files

  • config/
  • public/
  • src/
  • templates/
  • tests/

public/index.php

The front controller. Every request enters here and is routed by its path. Logic goes to Greeting and HTML to the templates. The web root is this public/ folder.

<?phpdeclare(strict_types=1); use App\Greeting;use App\View; require dirname(__DIR__) . '/vendor/autoload.php'; $config = require dirname(__DIR__) . '/config/app.php';$view = new View(dirname(__DIR__) . '/templates');$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/'; if ($path === '/') {    $message = (new Greeting())->for((string)($_GET['name'] ?? ''));    echo $view->render('home', ['title' => $config['name'], 'message' => $message]);    return;} http_response_code(404);echo $view->render('not-found', ['title' => $config['name']]);

Layers

Versions written in the files PHP 8.3+ · Composer 2 · PHPUnit 11. The vendor folder is not in the zip. With Composer, composer install downloads it; without Composer the project runs as is.

Standard PHP project folders

PathWhat goes there
public/The web server document root. Only the front controller index.php plus CSS and images. Files outside it cannot be opened by URL.
public/index.phpThe front controller. Every request enters here and is sent to the right code by its path.
src/Class code. With PSR-4, App\Greeting lives in src/Greeting.php.
config/Settings. No passwords or keys; read those from environment variables.
templates/PHP files that build HTML. They calculate nothing; they escape and print what they are given.
tests/Test code (PHPUnit). It does not need to go to the production server.
vendor/Packages and autoload.php installed by Composer. Never edit it and keep it out of git.
var/Files created at run time, such as logs and cache. Keep them out of git.

With public/ as the only web root, nothing in config/, src/ or vendor/ can leak through a URL. On shared hosting where the root cannot move, put the contents of public/ in the root and everything else one folder above it.

Splitting into layers

Put the part that takes requests (controller), the part that decides rules (service) and the part that stores data (repository) in separate classes. Calls go front controller, controller, service, repository, never backwards.

Then storage can move from an array to MySQL without touching the service, and PHPUnit can check service rules without a web server.

  • A controller reads $_GET and $_POST and builds the response; it calculates nothing.
  • A service decides the rules and knows nothing about $_GET.
  • Describe the repository with an interface and swap array and database versions freely.

Naming and PSR

A Composer package name looks like vendor/package in lowercase with -; a namespace uses capitalized words such as App or Acme\Shop.

  • PSR-1: classes in StudlyCaps, methods in camelCase, constants in UPPER_CASE.
  • PSR-4: a namespace prefix maps to one folder and the rest of the name becomes the path (App\Http\Router to src/Http/Router.php).
  • PSR-12: four-space indents, opening braces of classes and methods on the next line, no closing ?> at the end of a file.
  • Keep passwords and API keys out of code; read them with getenv().

Four common design patterns and dependency injection

PHP has closures and anonymous classes, so small patterns need fewer classes. All of this code was run on server PHP and browser PHP.

Singleton · when there must be exactly one

A private constructor blocks new, and a static slot remembers the first object, which is returned every time. ??= assigns only when the slot is empty.

PHP starts fresh on every request, so "one" means one per request. Singletons make testing harder; creating one object in the front controller and passing it in (dependency injection) is usually better.

<?phpdeclare(strict_types=1); final class Settings{    private static ?Settings $instance = null;    private array $values = ['lang' => 'en'];     private function __construct()    {    }     public static function get(): Settings    {        return self::$instance ??= new Settings();    }     public function set(string $key, string $value): void    {        $this->values[$key] = $value;    }     public function value(string $key): string    {        return $this->values[$key] ?? '';    }} $a = Settings::get();$b = Settings::get();$b->set('lang', 'ko');var_dump($a === $b);echo $a->value('lang'), "\n";

Output

bool(true)ko

Factory · deciding what to create in one place

Look at the format name and return the matching exporter. match falls to default when nothing matches, and can throw right there (throw is an expression since 8.0). Case is normalized in the same spot.

<?phpdeclare(strict_types=1); interface Exporter{    public function export(array $row): string;} final class CsvExporter implements Exporter{    public function export(array $row): string    {        return implode(',', $row);    }} final class JsonExporter implements Exporter{    public function export(array $row): string    {        return json_encode($row);    }} final class ExporterFactory{    public static function for(string $format): Exporter    {        return match (strtolower($format)) {            'csv' => new CsvExporter(),            'json' => new JsonExporter(),            default => throw new InvalidArgumentException("unknown format: $format"),        };    }} $row = ['id' => 7, 'name' => 'Lee'];echo ExporterFactory::for('CSV')->export($row), "\n";echo ExporterFactory::for('json')->export($row), "\n";try {    ExporterFactory::for('xml');} catch (InvalidArgumentException $e) {    echo $e->getMessage(), "\n";}

Output

7,Lee{"id":7,"name":"Lee"}unknown format: xml

Strategy · swappable ways to calculate

Each discount rule is an arrow function (fn) handed to Cart. A function stored in a property is called with extra parentheses: ($this->discount)(...). A rule that needs settings, like $coupon(3000), is a function that returns a function.

<?phpdeclare(strict_types=1); final class Cart{    /** @param callable(int): int $discount */    public function __construct(private int $total, private $discount)    {    }     public function pay(): int    {        return ($this->discount)($this->total);    }} $none = fn(int $t): int => $t;$tenPercent = fn(int $t): int => $t - intdiv($t, 10);$coupon = fn(int $off): Closure => fn(int $t): int => max(0, $t - $off); foreach ([$none, $tenPercent, $coupon(3000)] as $rule) {    echo (new Cart(20000, $rule))->pay(), "\n";}

Output

200001800017000

Observer · telling others when something happens

When an event such as a restock happens, every registered function is called in turn. To change an outside array, capture it by reference with use (&$log); plain use ($log) changes a copy.

<?phpdeclare(strict_types=1); final class Stock{    /** @var list<callable(string): void> */    private array $listeners = [];     public function onRestock(callable $fn): void    {        $this->listeners[] = $fn;    }     public function restock(string $item): void    {        foreach ($this->listeners as $fn) {            $fn($item);        }    }} $log = [];$stock = new Stock();$stock->onRestock(function (string $item): void {    echo "Mail: $item is back\n";});$stock->onRestock(function (string $item) use (&$log): void {    $log[] = $item;});$stock->restock('keyboard');echo 'Log: ', implode(',', $log), "\n";

Output

Mail: keyboard is backLog: keyboard

Dependency injection · receiving what you need through the constructor

Greeter does not build its user store; it receives one in the constructor. Real code passes ArrayUserStore (a database version later), a test passes a fake made with an anonymous class (new class implements UserStore).

The service containers in Symfony and Laravel do the same job: they read constructor types and pass in the right objects.

<?phpdeclare(strict_types=1); interface UserStore{    public function find(int $id): ?string;} final class ArrayUserStore implements UserStore{    public function __construct(private array $names)    {    }     public function find(int $id): ?string    {        return $this->names[$id] ?? null;    }} final class Greeter{    public function __construct(private UserStore $users)    {    }     public function hello(int $id): string    {        return 'Hello, ' . ($this->users->find($id) ?? 'guest');    }} $greeter = new Greeter(new ArrayUserStore([1 => 'Hana']));echo $greeter->hello(1), "\n";echo $greeter->hello(2), "\n"; $fake = new class implements UserStore {    public function find(int $id): ?string    {        return 'Tester';    }};echo (new Greeter($fake))->hello(99), "\n";

Output

Hello, HanaHello, guestHello, Tester

Check yourself

Question 1

Which folder should be the web server document root?

Show the answer

Answer: 1. public/ Only public/. Then settings in config/ and code in src/ can never be opened by URL.

Question 2

With "App\\": "src/" in composer.json, where does the class App\Http\Router live?

Show the answer

Answer: 3. src/Http/Router.php PSR-4 replaces the prefix App\ with src/ and turns the rest, Http\Router, into folders and a file name: src/Http/Router.php. Match the case too, or a Linux server will not find it.

Questions people ask

Can I autoload classes without Composer?

Yes. A small spl_autoload_register function that maps the namespace to a folder is enough; choosing no Composer adds that file for you.

Does the vendor folder go into git?

No. Commit composer.json and composer.lock; others run composer install to get the same versions.

What should the web server root be?

Only the public folder. It is the easiest way to keep settings, code and vendor from being opened by URL.