Build a Simple PHP MVC Framework from Scratch – Step‑by‑Step Guide
This tutorial walks you through creating a basic PHP MVC framework, covering the MVC pattern concepts, required prerequisites, project setup with Composer, directory structure, core components like routing and controllers, view rendering, model creation, and testing the application.
MVC is a common design pattern in software development, especially for web applications, that separates an application into three interconnected components: Model, View, and Controller, improving modularity, maintainability, and development ease.
Model (M) represents the application's data and business logic, handling data retrieval, manipulation, and storage.
View (V) acts as the presentation layer, responsible for displaying data to the end user.
Controller (C) mediates between model and view, receiving user input and determining which model(s) to invoke and which view to render.
The MVC pattern enforces separation of concerns, making applications easier to understand, maintain, and extend.
Prerequisites
In this tutorial you will build a simple PHP MVC framework from scratch. You should have a basic understanding of:
Composer – the PHP package manager
HTML/CSS – not required for the framework itself but needed for the resulting pages
Project Setup
To create a new Composer project, follow these steps:
Create a new directory and name it for your project.
Open the directory in your editor.
Run composer init in the terminal. composer init During composer init, press Enter to skip all questions except development dependencies, and type no when asked to add dependencies. Then change the namespace key in composer.json from "Maheshsamudra\\SimplePhpMvcStarter\\" to "App\\" and run composer dump-autoload to update the autoloader.
Directory Structure
public/ # web root
src/
Controllers/
Models/
Routes/
Views/
vendor/ # generated by ComposerBuild Core Components
Set Up Public Folder
Create public/index.php as the application entry point:
<?php
require '../vendor/autoload.php';
$router = require '../src/Routes/index.php';Routing
Create src/Router.php to map routes to controllers:
<?php
namespace App;
class Router {
protected $routes = [];
private function addRoute($route, $controller, $action, $method) {
$this->routes[$method][$route] = ['controller' => $controller, 'action' => $action];
}
public function get($route, $controller, $action) {
$this->addRoute($route, $controller, $action, "GET");
}
public function post($route, $controller, $action) {
$this->addRoute($route, $controller, $action, "POST");
}
public function dispatch() {
$uri = strtok($_SERVER['REQUEST_URI'], '?');
$method = $_SERVER['REQUEST_METHOD'];
if (array_key_exists($uri, $this->routes[$method])) {
$controller = $this->routes[$method][$uri]['controller'];
$action = $this->routes[$method][$uri]['action'];
$controller = new $controller();
$controller->$action();
} else {
throw new \Exception("No route found for URI: $uri");
}
}
}Create src/Routes.php to define the initial route:
<?php
use App\Controllers\HomeController;
use App\Router;
$router = new Router();
$router->get('/', HomeController::class, 'index');
$router->dispatch();Controller – Handling the Home Page
Create a base controller in src/Controller.php:
<?php
namespace App;
class Controller {
protected function render($view, $data = []) {
extract($data);
include "Views/$view.php";
}
}Then create src/Controllers/HomeController.php:
<?php
namespace App\Controllers;
use App\Controller;
class HomeController extends Controller {
public function index() {
$this->render('index');
}
}Add a View
Create src/Views/index.php:
<h1>Welcome to Simple PHP MVC Starter!</h1>Test the Application
Run the built‑in PHP web server from the project root:
cd simple-php-mvc-starter
php -S localhost:9999If everything works, you should see the welcome message in the browser.
Create a Model
Add src/Models/Journal.php to represent a journal entity:
<?php
namespace App\Models;
class Journal {
public $name;
public $publishedYear;
public function __construct($name, $publishedYear) {
$this->name = $name;
$this->publishedYear = $publishedYear;
}
}Update HomeController.php to load journals and pass them to the view, then modify Views/index.php to display the list:
<?php
// Inside HomeController::index()
use App\Models\Journal;
$journals = [
new Journal('Journal A', 2020),
new Journal('Journal B', 2021)
];
$this->render('index', ['journals' => $journals]); <h1>Welcome to Simple PHP MVC Starter!</h1>
<ul>
<?php foreach ($journals as $journal) : ?>
<li><?= $journal->name ?> (<?= $journal->publishedYear ?>)</li>
<?php endforeach; ?>
</ul>That’s it—you have successfully built your first PHP MVC framework.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
