A small application
Build on Hello world with a list of articles, a detail page and a form that adds a new article. This example connects routing, a small model, DI and PHP views. All application files are supplied below.
Articles are stored in a JSON file for this single-user exercise. Writes happen one at a time; simultaneous writes are not supported. This is one small application’s storage choice, not an Unphramed requirement. No database, login or Unphramed package is needed.
On this page
Prepare the project
Use Composer and the same configured environment as Hello world. This application also needs shared initialization: set PHP's auto_prepend_file to the absolute path of bootstrap.php so the autoloader runs before each controller. Keep PHP error display disabled and logging enabled in that environment.
From the project directory:
mkdir -p config src/Entity src/Repository src/View var web/GET/articles web/POST
Create the following files. App is the namespace chosen for this example; your project may map a different namespace to src/. Keep its Composer mapping, declarations and imports consistent. If extending Hello world, replace its chosen routing file; the old hello controller can be removed.
File: composer.json
{
"name": "example/articles",
"type": "project",
"require": {
"php": "^8.3"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
The require section declares dependencies; this example only requires PHP. The PSR-4 mapping tells Composer that classes under App\ live in src/. Running composer install generates vendor/autoload.php even when no third-party library is needed. Composer can also install libraries you choose for your application; see its basic usage guide.
File: bootstrap.php
<?php
declare(strict_types=1);
require __DIR__ . "/vendor/autoload.php";
The bootstrap loads Composer's generated autoloader before the selected controller runs. Classes such as App\DI can then be loaded from src/ as they are used; DI constructs the objects the controller needs.
Routes
Choose the file for your server; the PHP files are identical with either choice.
File: config/nginx.conf
if ($uri ~ "\.php(?:/|$)") {
return 404;
}
location / { return 404; }
set $handler_method $request_method;
if ($request_method = HEAD) {
set $handler_method GET;
}
rewrite ^/$ /articles redirect;
rewrite ^/articles$ /$handler_method/articles.php last;
rewrite ^/articles/(\d+)$ /$handler_method/articles/[id].php?id=$1? last;
rewrite ^/articles/new$ /$handler_method/articles/new.php last;
File: config/apache.conf
RewriteEngine On
RewriteRule \.php(?:/|$) - [R=404,L]
RewriteRule ^ - [E=handler_method:%{REQUEST_METHOD}]
RewriteCond %{REQUEST_METHOD} ^HEAD$
RewriteRule ^ - [E=handler_method:GET]
RewriteRule ^/$ /articles [R=302,L]
RewriteRule ^/articles$ /%{ENV:handler_method}/articles.php
RewriteRule ^/articles/(\d+)$ /%{ENV:handler_method}/articles/[id].php?id=$1
RewriteRule ^/articles/new$ /%{ENV:handler_method}/articles/new.php
RewriteCond %{DOCUMENT_ROOT}$0 -f
RewriteRule ^/.*\.php$ - [PT]
RewriteRule ^ - [R=404,L]
The environment includes the chosen file inside Nginx’s server or Apache’s <VirtualHost> and provides the common PHP handler. GET lists articles or opens the form at /articles/new; POST submits to /articles, selecting a different PHP file through the same rewrite as the list. Methods without a file receive 404.
Model and DI
Entity\Article represents an article and holds the data used by the views. Repository\ArticleRepository retrieves articles and saves additions in var/articles.json; its constructor receives the file path. These names separate the model’s responsibilities in this example. Unphramed does not require these directories or this storage implementation.
File: src/Entity/Article.php
<?php
declare(strict_types=1);
namespace App\Entity;
final class Article
{
public function __construct(
public readonly string $id,
public readonly string $title,
public readonly string $body,
) {}
}
File: var/articles.json
[
{
"id": "1",
"title": "Follow a request",
"body": "The server selects a controller. The controller calls the model."
},
{
"id": "2",
"title": "PHP & HTML",
"body": "A view receives data and escapes it for HTML."
}
]
Create this file before running the application and allow the user running PHP to read and write it. Keep var/ outside the document root. The repository assumes this file contains the article records shown above; it does not create or repair it.
File: src/Repository/ArticleRepository.php
<?php
declare(strict_types=1);
namespace App\Repository;
use App\Entity\Article;
final class ArticleRepository
{
public function __construct(private string $file) {}
/** @return list<Article> */
public function all(): array
{
return \array_map(
static fn(object $row): Article => new Article($row->id, $row->title, $row->body),
\json_decode(\file_get_contents($this->file), flags: JSON_THROW_ON_ERROR),
);
}
public function find(string $id): ?Article
{
foreach ($this->all() as $article) {
if ($article->id === $id) {
return $article;
}
}
return null;
}
public function add(string $title, string $body): Article
{
$articles = $this->all();
$lastId = 0;
foreach ($articles as $article) {
$lastId = \max($lastId, (int) $article->id);
}
$article = new Article((string) ($lastId + 1), $title, $body);
$articles[] = $article;
if (\file_put_contents($this->file, \json_encode($articles, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n") === false) {
throw new \RuntimeException("Could not save the article");
}
return $article;
}
}
File: src/DI.php
<?php
declare(strict_types=1);
namespace App;
use App\Repository\ArticleRepository;
final class DI
{
public static function getArticleRepository(): ArticleRepository
{
return new ArticleRepository(__DIR__ . "/../var/articles.json");
}
}
This factory chooses the storage path and passes it to the repository. ArticleRepository does not call DI or read HTTP parameters. The DI example shows a graph with several dependencies and explicit sharing.
Views
The base class declares the rendering contract. The layout wraps any such view in an HTML document.
File: src/View.php
<?php
declare(strict_types=1);
namespace App;
abstract class View
{
abstract public function __invoke(): void;
}
File: src/View/Layout.php
<?php
declare(strict_types=1);
namespace App\View;
use App\View;
final class Layout
{
public function __construct(private string $title) {}
public function __invoke(View $view): void
{
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= \htmlspecialchars($this->title, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") ?></title>
</head>
<body>
<nav><a href="/articles">Articles</a> · <a href="/articles/new">Add an article</a></nav>
<main><?php $view(); ?></main>
</body>
</html>
<?php
}
}
File: src/View/ArticleList.php
<?php
declare(strict_types=1);
namespace App\View;
use App\Entity\Article;
use App\View;
final class ArticleList extends View
{
/** @param list<Article> $articles */
public function __construct(private array $articles) {}
public function __invoke(): void
{
?>
<h1>Articles</h1>
<ul>
<?php foreach ($this->articles as $article): ?>
<li>
<a href="/articles/<?= \htmlspecialchars($article->id, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") ?>">
<?= \htmlspecialchars($article->title, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") ?>
</a>
</li>
<?php endforeach ?>
</ul>
<?php
}
}
File: src/View/ArticlePage.php
<?php
declare(strict_types=1);
namespace App\View;
use App\Entity\Article;
use App\View;
final class ArticlePage extends View
{
public function __construct(private Article $article) {}
public function __invoke(): void
{
?>
<article>
<h1><?= \htmlspecialchars($this->article->title, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") ?></h1>
<p><?= \nl2br(\htmlspecialchars($this->article->body, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8"), false) ?></p>
</article>
<?php
}
}
File: src/View/ArticleForm.php
<?php
declare(strict_types=1);
namespace App\View;
use App\View;
final class ArticleForm extends View
{
public function __invoke(): void
{
?>
<h1>Add an article</h1>
<form method="post" action="/articles">
<p><label>Title <input name="title" required></label></p>
<p><label>Body <textarea name="body" required></textarea></label></p>
<button type="submit">Add article</button>
</form>
<?php
}
}
Controllers
Each public PHP file handles one action. The read controllers obtain the repository from DI, then pass its results to views.
File: web/GET/articles.php
<?php
declare(strict_types=1);
use App\DI;
use App\View\ArticleList;
use App\View\Layout;
(new Layout("Articles"))(new ArticleList(DI::getArticleRepository()->all()));
File: web/GET/articles/[id].php
<?php
declare(strict_types=1);
use App\DI;
use App\View\ArticlePage;
use App\View\Layout;
$article = DI::getArticleRepository()->find($_GET["id"]);
if ($article === null) {
http_response_code(404);
exit;
}
(new Layout($article->title))(new ArticlePage($article));
The server already captured the ID. It stays a string: 1 and 01 are different identifiers in this catalogue, and a very long numeric ID simply has no matching article.
File: web/GET/articles/new.php
<?php
declare(strict_types=1);
use App\View\Layout;
use App\View\ArticleForm;
(new Layout("Add an article"))(new ArticleForm());
File: web/POST/articles.php
<?php
declare(strict_types=1);
use App\DI;
$title = $_POST["title"] ?? null;
$body = $_POST["body"] ?? null;
if (!is_string($title) || !is_string($body) || trim($title) === "" || trim($body) === "") {
http_response_code(400);
exit;
}
$article = DI::getArticleRepository()->add($title, $body);
header("Location: /articles/" . $article->id, true, 303);
exit;
The POST controller checks the submitted values and asks the model to save the article. It then redirects to the article’s GET page with status 303. Refreshing that page does not repeat the POST. The model and views do not read HTTP parameters or call DI themselves.
Add another action
Editing or deleting uses the same boundaries; these extensions are not included in the files above. For example, route GET /articles/{id}/edit to web/GET/articles/[id]/edit.php to load the article and show a prefilled view. The existing detail rewrite can select web/POST/articles/[id].php to accept changes at POST /articles/{id}. A new rewrite for POST /articles/{id}/delete can select web/POST/articles/[id]/delete.php.
The controllers validate input, call the model and return 404 for a missing article. After a successful mutation, redirect with 303 to the detail or list page. The repository implements persistence, following the same single-user assumption as add(). Views receive data and render the forms.
Run it
composer install
php -l bootstrap.php
curl -i http://my-app.test/articles
curl -i 'http://my-app.test/articles/1?id=2'
curl -i http://my-app.test/articles/new
curl -i --data-urlencode 'title=My <draft>' --data-urlencode 'body=Hello & welcome' http://my-app.test/articles
Have the environment validate and reload the routes first. The list should show two articles. The detail request should still show article 1 despite ?id=2. The POST should return 303 with a Location header for the new article. Open that URL to see the escaped title and body, then return to the list: the third article is saved in the JSON file and remains after a restart of the PHP-serving processes.
Try an unknown article, a direct /GET/articles/[id].php URL and POST /articles/new: each returns 404. Missing, blank or array-valued form fields return 400 without adding an article. You can also open /articles/new in a browser and submit the form normally.
You now have the complete path: the web server selects a PHP controller, PHP constructs its dependencies, the model supplies data, and a view renders it.