Architecture

Building a Reusable Application Structure with Plain PHP

Create a small reusable foundation for a plain PHP application using a front controller, routing, controllers, and shared services.

Use a front controller

A front controller gives the application one public entry point:

<?php
// public/index.php

require dirname(__DIR__) . '/vendor/autoload.php';

$app = require dirname(__DIR__) . '/bootstrap/app.php';
$app->run();

The bootstrap file can load configuration and construct the router and required services.

Keep routes explicit

A lightweight route definition might look like:

$router->get('/', [HomeController::class, 'index']);
$router->get('/articles/{slug}', [ArticleController::class, 'show']);
$router->post('/contact', [ContactController::class, 'submit']);

The router should match paths and HTTP methods, validate route parameters, and return a proper 404 response when no route matches.

Inject dependencies

Prefer passing a PDO connection or repository into a controller rather than creating a new database connection inside every action. This makes code easier to test and maintain.

Handle output safely

Views should escape untrusted values before rendering HTML. State-changing routes should validate input, enforce authorization, and use CSRF protection where appropriate.

Avoid building a framework prematurely

A reusable structure should solve real project needs. Keep routing, configuration, database access, and error handling small and understandable until the application requires more sophisticated components.