Lesson 6 of 6
Mini Project: Blog System - Part 10 (Full MVC Application)
Assemble everything into a complete MVC Blog - versioned routing, middleware pipeline (logging, auth, CSRF), event system for post publishing (sends notifications), Monolog structured logging, and a clean dependency injection container wiring all layers together.
Blog Part 10 - MVC Bootstrap & Event System
<?php
declare(strict_types=1);
// public/index.php - full MVC bootstrap
require __DIR__ . "/../vendor/autoload.php";
use DotenvDotenv;
use MonologLogger;
use MonologHandlerStreamHandler;
use MonologLevel;
$dotenv = Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();
// ── Container - wires all dependencies ────────────────────────
class Container {
private array $bindings = [];
private array $singletons = [];
public function singleton(string $id, callable $factory): void {
$this->bindings[$id] = ["factory" => $factory, "shared" => true];
}
public function bind(string $id, callable $factory): void {
$this->bindings[$id] = ["factory" => $factory, "shared" => false];
}
public function get(string $id): mixed {
if (!isset($this->bindings[$id])) throw new RuntimeException("No binding for: $id");
if ($this->bindings[$id]["shared"]) {
return $this->singletons[$id] ??= ($this->bindings[$id]["factory"])($this);
}
return ($this->bindings[$id]["factory"])($this);
}
}
$c = new Container();
// Infrastructure
$c->singleton(PDO::class, fn() => new PDO(
$_ENV["DB_DSN"] ?? "mysql:host=localhost;dbname=blog;charset=utf8mb4",
$_ENV["DB_USER"] ?? "root",
$_ENV["DB_PASSWORD"] ?? "",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false]
));
$c->singleton(Logger::class, fn() => createLogger("blog"));
$c->singleton(EventDispatcher::class, fn($c) => bootstrapEvents($c));
// Repositories / Services
$c->singleton(PostRepositoryInterface::class, fn($c) => new PdoPostRepository($c->get(PDO::class)));
$c->singleton(PostService::class, fn($c) => new PostService($c->get(PostRepositoryInterface::class), $c->get(EventDispatcher::class)));
$c->singleton(AuthService::class, fn($c) => new AuthService($c->get(PDO::class)));
// Controllers
$c->bind(PostController::class, fn($c) => new PostController($c->get(PostService::class)));
function bootstrapEvents(Container $c): EventDispatcher {
$d = new EventDispatcher();
$d->listen(PostPublished::class, new SendPublishNotification($c->get(Logger::class)));
$d->listen(UserRegistered::class, new SendWelcomeEmail($c->get(Logger::class)));
return $d;
}
// ── Session security ──────────────────────────────────────────
ini_set("session.cookie_httponly", "1");
ini_set("session.cookie_secure", ($_ENV["APP_ENV"] ?? "production") === "production" ? "1" : "0");
ini_set("session.cookie_samesite", "Strict");
session_start();
// ── Request & Pipeline ────────────────────────────────────────
$request = Request::fromGlobals();
$pipeline = (new Pipeline())
->pipe(new LoggingMiddleware($c->get(Logger::class)))
->pipe(new SecurityHeadersMiddleware());
// ── Router ────────────────────────────────────────────────────
$router = new Router();
// Public routes
$router->get("/", fn($req) => $c->get(PostController::class)->index($req));
$router->get("/posts/{slug}", fn($req) => $c->get(PostController::class)->show($req));
$router->get("/login", fn($req) => $c->get(AuthController::class)->showLogin($req));
$router->post("/login", fn($req) => $c->get(AuthController::class)->login($req));
$router->post("/logout", fn($req) => $c->get(AuthController::class)->logout($req));
// Auth-protected routes
$router->group([new AuthMiddleware(), new CsrfMiddleware()], function($r) use ($c) {
$r->get("/posts/create", fn($req) => $c->get(PostController::class)->create($req));
$r->post("/posts", fn($req) => $c->get(PostController::class)->store($req));
$r->get("/posts/{id}/edit", fn($req) => $c->get(PostController::class)->edit($req));
$r->put("/posts/{id}", fn($req) => $c->get(PostController::class)->update($req));
$r->delete("/posts/{id}", fn($req) => $c->get(PostController::class)->destroy($req));
});
// Dispatch
sendSecurityHeaders();
$response = $pipeline->run($request, fn($req) => $router->dispatch($req));
$response->send();Quick Quiz
Module Quiz
What is the purpose of the MVC Controller in a PHP application?
Tip
Tip
Practice Mini Project Blog System Part 10 Full MVC Application in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Mini Project: Blog System - Part 10 (Full MVC Application)
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Blog System Part 10 Full MVC Application from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Mini Project Blog System Part 10 Full MVC Application is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?