← Back to course: PHP from scratch

Architecture: a mini-MVC with a router

Video coming soon

Until now each URL corresponded to a PHP file: contact.php, login.php, cart.php. It works for examples, but in a real application the same session, connection and template code is repeated everywhere. The classic solution is the MVC pattern: separate the Model (data and rules), the View (the HTML that is shown) and the Controller (which receives the request, uses the model and chooses the view). In addition, a single entry point, called the front controller, receives all requests and distributes them through a router. This is how Laravel, Symfony and almost all frameworks work; today you will build a minimal version to understand how they work inside.

Folder structure

Only the public folder should be reachable from the browser: index.php and static files go there. The rest (src, templates, the database, vendor) stays outside the web root, so nobody can download your code or your SQLite file by mistake. The built-in server is launched pointing at that folder with php -S localhost:8000 -t public, and since index.php acts as the router for everything, pretty URLs such as /posts/3 reach it thanks to the router script (public/index.php) passed at the end of the command.

text
blog/
  composer.json          (autoload App\ => src/)
  public/
    index.php            (front controller)
  src/
    Router.php
    View.php
    Controller/PostController.php
    Repository/PostRepository.php
  templates/
    layout.php
    posts/index.php
    posts/show.php
  var/
    data.sqlite          (outside public)

Router and views

The router keeps a table of routes: an HTTP method, a URL pattern and a function or controller to run. In our version we use simple regular expressions to capture parameters such as the id. If no route matches, it answers 404. The view is a template file that receives an array of data and displays it; the function that loads it must always escape, which is why we define a helper e() available in templates. Keep logic out of templates: only simple conditionals and loops to display data.

php
<?php
// File: src/Router.php
declare(strict_types=1);

namespace App;

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

    public function add(string $method, string $path, callable $handler): void
    {
        // Turn /posts/{id} into a regular expression
        $pattern = '#^' . preg_replace('#\{(\w+)\}#', '(?P<$1>[^/]+)', $path) . '$#';
        $this->routes[] = ['method' => $method, 'pattern' => $pattern, 'handler' => $handler];
    }

    public function dispatch(string $method, string $uri): void
    {
        $path = parse_url($uri, PHP_URL_PATH) ?: '/';

        foreach ($this->routes as $route) {
            if ($route['method'] === $method && preg_match($route['pattern'], $path, $matches) === 1) {
                $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
                ($route['handler'])(...$params);
                return;
            }
        }

        http_response_code(404);
        echo 'Page not found';
    }
}
php
<?php
// File: src/View.php
declare(strict_types=1);

namespace App;

final class View
{
    /** @param array<string, mixed> $data */
    public static function render(string $template, array $data = []): void
    {
        $file = __DIR__ . '/../templates/' . $template . '.php';
        extract($data, EXTR_SKIP);   // each key becomes a variable in the template
        require $file;
    }
}

function e(string $text): string
{
    return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

Controller, repository and front controller

The repository concentrates the SQL queries of an entity and returns arrays or objects, so the controller knows nothing about SQL. The controller receives parameters, asks the repository for data and calls the view. The front controller, public/index.php, loads the autoload, opens the database, registers the routes and calls dispatch. Notice that the id arrives as text from the URL: convert it with (int) and validate that it exists before using it. This separation makes each piece small, easy to understand and easy to test.

php
<?php
// File: src/Repository/PostRepository.php
declare(strict_types=1);

namespace App\Repository;

use PDO;

final class PostRepository
{
    public function __construct(private PDO $pdo)
    {
    }

    /** @return list<array<string, mixed>> */
    public function all(): array
    {
        return $this->pdo->query('SELECT id, title, created_at FROM posts ORDER BY id DESC')->fetchAll();
    }

    /** @return array<string, mixed>|null */
    public function find(int $id): ?array
    {
        $stmt = $this->pdo->prepare('SELECT id, title, body, created_at FROM posts WHERE id = :id');
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch();
        return $row === false ? null : $row;
    }
}
php
<?php
// File: src/Controller/PostController.php
declare(strict_types=1);

namespace App\Controller;

use App\Repository\PostRepository;
use App\View;

final class PostController
{
    public function __construct(private PostRepository $posts)
    {
    }

    public function index(): void
    {
        View::render('posts/index', ['posts' => $this->posts->all()]);
    }

    public function show(string $id): void
    {
        $post = $this->posts->find((int) $id);
        if ($post === null) {
            http_response_code(404);
            echo 'Post not found';
            return;
        }
        View::render('posts/show', ['post' => $post]);
    }
}
php
<?php
// File: public/index.php   (run: php -S localhost:8000 -t public public/index.php)
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../src/View.php'; // defines the e() helper (a plain function)

use App\Controller\PostController;
use App\Repository\PostRepository;
use App\Router;

$pdo = new PDO('sqlite:' . __DIR__ . '/../var/data.sqlite', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$controller = new PostController(new PostRepository($pdo));

$router = new Router();
$router->add('GET', '/', [$controller, 'index']);
$router->add('GET', '/posts/{id}', [$controller, 'show']);

$router->dispatch($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);

Test what you learned

Question 1 of 1

What role does the controller play in MVC?

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →