TeóriaTheory UkážkyExamples Úlohy na cvičenieLab tasks Obhajoba a live codingDefence and live coding
Dnes aplikácia začne odpovedať na viac adries. Doteraz mala jednu stránku, index.php. Od dnes má adresu …/cv03/recipes pre zoznam, …/cv03/recipes/3 pre jeden záznam a stránku 404 pre všetko ostatné. Robia to riadky RewriteEngine, RewriteCond a RewriteRule v .htaccess, trieda Router a priečinok views/ s HTML každej stránky. Na konci cvičenia máš vo svojom webovom priestore na sigma.tuke.sk aplikáciu, v ktorej sa dá klikať medzi zoznamom a detailom záznamov. Pojmy sú v tabuľke pojmov.
Today the application starts answering more than one address. So far it had one page, index.php. From today it has …/cv03/recipes for a list, …/cv03/recipes/3 for one record and a 404 page for everything else. Three new things do this: three lines in .htaccess, the Router class and the views/ folder with the HTML of each page. At the end of the lab you have an application in your web space on sigma.tuke.sk where you can click between a list and a record’s detail. Terms are in the table of terms.
TeóriaTheory
Čo dnes dostaneš a čo s tým urobíš
Východisko je repository cv02: kontrolná stránka funguje, modely sú v src/Model/, databáza má dáta. Výsledok je repository cv03, v ktorom aplikácia odpovedá na tieto adresy (názvy categories a recipes sú zo vzorovej aplikácie; u teba sú to názvy tvojich tabuliek):
| Adresa v prehliadači | Čo sa zobrazí | Časť |
|---|---|---|
https://sigma.tuke.sk/student/meno.priezvisko/it/cv03/ |
úvodná stránka | 5 |
…/it/cv03/kontrola |
kontrolná stránka z cv02 | 6 |
…/it/cv03/categories |
tabuľka záznamov číselníka | Ukážka 3 |
…/it/cv03/recipes |
tabuľka záznamov hlavnej entity, id je odkaz na detail |
Ukážka 3 |
…/it/cv03/recipes/3 |
jeden záznam hlavnej entity s id 3 |
Ukážka 3 |
…/it/cv03/debug |
pomocná stránka: čo prišlo na server a čo z toho aplikácia vypočítala | 4 |
…/it/cv03/cokolvek-ine |
stránka „Nenájdené“ so stavovým kódom 404 (časť 2) | 2, 5 |
Z webu predmetu stiahneš router.zip (stiahnutie kliknutím, alebo príkazom curl v úlohe 4.1). Je v ňom 10 súborov:
.htaccess nahradí .htaccess z cv02: pribudli 3 riadky (časť 3)
composer.json nahradí composer.json z cv02: pribudol blok "files" (časť 7)
index.php nahradí index.php z cv02: nový obsah (časť 5)
src/Router.php nový: trieda Router (časť 5)
src/helpers.php nový: funkcie e(), url(), view() (časť 6)
views/layout.php nový: spoločný HTML rám každej stránky (časť 6)
views/home.php nový: obsah úvodnej stránky (časť 6)
views/404.php nový: obsah stránky „Nenájdené“ (časť 6)
views/debug.php nový: obsah pomocnej stránky (časť 4)
views/kontrola.php nový: kontrolná stránka z cv02 bez HTML rámu; doplníš svoje modely (časť 6)
Postup je v úlohe 4.1. V skratke: repository cv03 naklonuješ do ~/web/it/cv03, skopíruješ doň z cv02 súbory, ktoré sa nemenia, rozbalíš router.zip, spustíš composer install a priečinok nahráš na sigma.tuke.sk.
Z cv02 kopíruješ tieto súbory a priečinky (menia sa len tie, ktoré sú v router.zip):
cd ~/web/it
cp cv02/config.php cv03/
cp cv02/config.example.php cv03/
cp cv02/.gitignore cv03/
cp -r cv02/sql cv03/
cp -r cv02/src cv03/
| Riadok | Poznámka |
|---|---|
| 1 | priečinok, v ktorom sú vedľa seba cv02 a cv03 |
| 2 | prihlasovacie údaje k databáze; sú rovnaké, databáza je tá istá |
| 3–4 | vzor konfigurácie a zoznam pre Git; bez zmeny |
| 5 | schema.sql a seed.sql; -r kopíruje priečinok aj s obsahom |
| 6 | Database.php a Model/ s tvojimi modelmi; router.zip do src/ pridá Router.php a helpers.php |
Z cv02 nekopíruješ:
| Súbor / priečinok | Prečo |
|---|---|
.git/ |
história repository cv02; cv03 má vlastnú históriu, ktorá začala pri clone |
vendor/ |
výsledok príkazu composer install; v cv03 ho vytvoríš znova, lebo composer.json sa zmenil |
.htaccess, composer.json, index.php |
nová verzia je v router.zip |
README.md |
cv03 má vlastný s úlohami tohto týždňa |
Kde čo je po úlohe 4.1:
| Súbor | Kubeflow ~/web/it/cv03 |
sigma.tuke.sk public_html/it/cv03 |
GitHub cv03-login |
|---|---|---|---|
index.php, .htaccess, composer.json, src/, views/, sql/ |
áno | áno (uloženie v editore, Upload Folder) | áno |
config.php |
áno | áno (uloženie v editore) | nie (.gitignore) |
vendor/ |
áno (composer install) |
áno (Upload Folder) | nie (.gitignore) |
HTTP: požiadavka a odpoveď
HTTP sú pravidlá, podľa ktorých sa rozprávajú prehliadač a server. Rozhovor má vždy dva kroky: prehliadač pošle požiadavku (request), server vráti odpoveď (response). Jedna požiadavka, jedna odpoveď.
Kde požiadavka vzniká: v prehliadači. Napíšeš adresu do riadka s adresou a stlačíš Enter, alebo klikneš na odkaz, alebo odošleš formulár. Prehliadač zostaví text požiadavky a pošle ho serveru sigma.tuke.sk.
Kto požiadavku napíše: prehliadač. Ty napíšeš adresu, prehliadač ju rozloží na riadky a tie pošle. Nikde sa to nepíše rukou a v okne prehliadača to nevidíš; prehliadač to ukáže len v karte Network (koniec tejto časti).
Čo je v požiadavke. Napíšeš https://sigma.tuke.sk/student/meno.priezvisko/it/cv03/recipes/3, prehliadač z adresy zostaví a pošle tento text (prvé tri riadky):
GET /student/meno.priezvisko/it/cv03/recipes/3 HTTP/1.1
Host: sigma.tuke.sk
Accept: text/html
| Riadok | Poznámka |
|---|---|
| 1 | GET je HTTP metóda: druh požiadavky. Za ňou je cesta: časť adresy za názvom servera. S cestou dnes pracuje celá aplikácia. |
| 2 | názov servera, ktorému je požiadavka určená |
| 3 | čo prehliadač chce dostať; pre stránky vždy HTML |
Z ktorej časti adresy je ktorý riadok:
| Časť adresy | Kam ju prehliadač dá |
|---|---|
https:// |
nikam; hovorí len, že prenos je šifrovaný |
sigma.tuke.sk |
riadok 2, Host:; všetko medzi // a prvou lomkou |
/student/meno.priezvisko/it/cv03/recipes/3 |
riadok 1, cesta; všetko od prvej lomky po koniec (bez časti za ?) |
slovo GET |
riadok 1, metóda; prehliadač ho dá, lebo si adresu napísala alebo klikla na odkaz; pri odoslaní formulára s method="post" dá POST |
HTTP/1.1, Accept: text/html |
riadok 1 koniec a riadok 3; prehliadač má pevne |
Každý súbor je samostatná požiadavka: stránka je jedna požiadavka, každý obrázok a každý súbor CSS v nej je ďalšia požiadavka. Preto má karta Network pre jednu stránku viac riadkov.
HTTP metódy, s ktorými v predmete pracuješ:
| Metóda | Kedy ju prehliadač pošle | Kde sú dáta |
|---|---|---|
GET |
adresa + Enter, klik na odkaz, formulár s method="get" |
v adrese za ?: ?q=abc je v PHP $_GET['q'] |
POST |
formulár s method="post" |
v tele požiadavky, v PHP $_POST |
PUT, DELETE |
zo stránky ich prehliadač sám nepošle; posiela ich program (JavaScript, iná aplikácia) | v tele požiadavky |
Dnes pracuješ len s GET.
$_SERVER je pole, ktoré Apache naplní pre PHP pri každej požiadavke, rovnako ako $_GET a $_POST. Z riadkov požiadavky v ňom je: HTTP metóda v $_SERVER['REQUEST_METHOD'] (GET), cesta v $_SERVER['REQUEST_URI'] (/student/meno.priezvisko/it/cv03/recipes/3), server v $_SERVER['HTTP_HOST'] (sigma.tuke.sk). Apache doň pridá aj cestu k súboru, ktorý spustil: $_SERVER['SCRIPT_NAME'] (časť 4).
Kde požiadavka dorazí: na server sigma.tuke.sk, do programu Apache. Apache podľa cesty vyberie súbor v tvojom webovom priestore (public_html/it/cv03/…), súbor .php spustí a všetko, čo PHP vypíše (echo, HTML za ?>), pošle späť ako odpoveď.
Kto odpoveď napíše: dvaja. PHP napíše telo (všetko, čo vypíše echo a HTML za ?>). Prvý riadok a hlavičky dopíše Apache sám; do prvého riadku dá 200 OK, ak PHP nepovedalo inak. PHP povie inak zavolaním http_response_code(404): od tej chvíle dá Apache do prvého riadku 404 Not Found.
Čo je v odpovedi:
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
<!doctype html>
<html lang="sk">
| Riadok | Poznámka |
|---|---|
| 1 | stavový kód: číslo, ktoré hovorí, ako požiadavka dopadla |
| 2 | typ obsahu v tele |
| 4–5 | telo odpovede: to, čo vypísalo PHP; prehliadač ho zobrazí |
Stavové kódy, ktoré dnes použiješ:
| Kód | Význam | Kedy ho pošle tvoja aplikácia |
|---|---|---|
200 OK |
stránka existuje, tu je | každá nájdená stránka; dopíše ho Apache, do kódu nič nepíšeš |
404 Not Found |
pre túto cestu nemám stránku | cesta, pre ktorú Router nemá záznam; zapíše ho riadok http_response_code(404); v Router::dispatch() (časť 5) |
500 Internal Server Error |
PHP skončilo chybou | chyba v kóde; text chyby vidíš, lebo config.php má 'debug' => true |
Kde odpoveď dorazí: späť do prehliadača. Telo sa zobrazí v okne. Prvý riadok a hlavičky prehliadač nezobrazí, ale ukáže ich: stlač F12, klikni na kartu Network (Sieť), obnov stránku (F5), klikni na prvý riadok v zozname, vpravo karta Headers. Hore je Status Code (stavový kód), nižšie Request Headers (požiadavka) a Response Headers (odpoveď). Obrázok je v Ukážke 1.
Viac: MDN: HTTP overview
.htaccess: prepisovanie ciest
.htaccess je textový súbor s názvom presne .htaccess (bodka na začiatku, bez prípony), uložený v priečinku na serveri. Apache ho prečíta pri každej požiadavke, ktorá smeruje do tohto priečinka alebo jeho podpriečinkov, a riadi sa príkazmi v ňom. Príkaz v .htaccess sa volá direktíva: jeden riadok, prvé slovo je názov direktívy, za ním parametre.
Kde je: v koreni aplikácie, vedľa index.php: ~/web/it/cv03/.htaccess v Kubeflow, public_html/it/cv03/.htaccess na sigma.tuke.sk, v repository na GitHub. Meno začína bodkou, Linux ho považuje za skrytý: v termináli ho ukáže ls -a, Explorer vo VS Code ho ukáže sivšie, WinSCP len so zapnutým zobrazovaním skrytých súborov.
Kedy sa použije: pri každej požiadavke, bez reštartu a bez spúšťania. Uložíš súbor v editore (SFTP ho prenesie na sigma.tuke.sk) a ďalšia požiadavka už ide podľa nového obsahu. Preklep v názve direktívy znamená, že každá požiadavka do priečinka dostane stavový kód 500. Oprava je oprava riadku a uloženie.
Čo sa dá v .htaccess nastaviť:
| Skupina direktív | Príklad | Na čo | U nás |
|---|---|---|---|
| prístup k súborom | Require all denied |
súbor sa z prehliadača nedá otvoriť | config.php (cv02) |
| odpoveď pre vzor cesty | RedirectMatch 404 … |
pre cesty, ktoré sedia na vzor, vrátiť stavový kód | src, vendor, sql, .git (cv02) |
| výpis priečinka | IndexIgnore * |
priečinok bez index.php nevypíše svoj obsah |
cv02 |
| prepisovanie ciest | RewriteRule |
požiadavku na jednu cestu obslúžiť iným súborom | dnes |
| chybové stránky | ErrorDocument 404 /chyba.html |
vlastný súbor pre stavový kód | nie; stránku 404 robí Router |
| heslo na priečinok | AuthType Basic + Require valid-user |
priečinok chránený menom a heslom | nie |
| nastavenia PHP | php_value upload_max_filesize 8M |
zmena nastavenia PHP pre tento priečinok | nie |
Na sigma.tuke.sk sú pre .htaccess povolené všetky skupiny z tabuľky.
Celý .htaccess pre cv03 (riadky 1–10 sú z cv02, riadky 12–15 sú nové):
# Priečinky s kódom a SQL nie sú stránky.
RedirectMatch 404 /(src|vendor|sql|\.git)(/|$)
# Súbor s heslom k databáze sa cez web nedá otvoriť.
<Files "config.php">
Require all denied
</Files>
# Priečinok bez index.php nevypíše svoj obsah.
IndexIgnore *
# Prepisovanie ciest: každá cesta, ktorá nie je existujúci súbor, ide do index.php.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
| Riadok | Poznámka |
|---|---|
| 2, 5–7, 10 | z cv02; máš ich v projekte od kostry (vysvetlenie .htaccess kostry) |
| 13 | zapne modul Apache na prepisovanie ciest (mod_rewrite). Bez tohto riadku Apache riadky 14 a 15 ignoruje. |
| 14 | podmienka pre nasledujúci RewriteRule. %{REQUEST_FILENAME} je súbor na disku, ktorý zodpovedá ceste z požiadavky. !-f znamená „nie je to existujúci súbor“. Pre /recipes/3 podmienka platí (súbor recipes/3 v priečinku nie je). Pre /css/style.css neplatí (súbor existuje). |
| 15 | pravidlo: ak podmienka platí, požiadavku obslúž súborom index.php. ^ sedí na každú cestu. [L] znamená posledné pravidlo, ďalšie sa nehľadajú. |
Čo sa stane s konkrétnou požiadavkou:
| Prehliadač žiada | Existuje súbor? | Apache spustí |
|---|---|---|
…/cv03/recipes/3 |
nie | index.php; pôvodná cesta /…/cv03/recipes/3 ostáva v $_SERVER['REQUEST_URI'] (časť 4) |
…/cv03/css/style.css |
áno | pošle css/style.css; index.php sa nespustí |
…/cv03/ |
priečinok; Apache v ňom hľadá index.php |
index.php |
…/cv03/src/Router.php |
áno, ale riadok 2 platí skôr | odpoveď 404 |
Ako overíš, že riadky 13–15 fungujú: otvor …/cv03/debug. Zobrazí sa tabuľka s piatimi riadkami (časť 4): prepisovanie beží. Zobrazí sa stránka Apache „Not Found“ bez menu tvojej aplikácie: prepisovanie nebeží; skontroluj, že .htaccess je na sigma.tuke.sk a má riadok RewriteEngine On.
Viac: Apache: mod_rewrite
Prefix a relatívna adresa
Prefix je časť cesty, ktorá je vo všetkých adresách tvojej aplikácie rovnaká: /student/meno.priezvisko/it/cv03. U každého študenta je iný, u učiteľa je /beata.stehlikova/it/ukazky/cv03.
Relatívna adresa je cesta bez prefixu: /, /recipes, /recipes/3. Router (časť 5) pracuje len s relatívnou adresou. Preto je ten istý index.php správny u každého študenta aj u učiteľa.
Relatívnu adresu vyrobia štyri riadky v index.php, piaty si odloží prefix. Sú to riadky 18–22 v index.php (časť 5) a spustia sa pri každej požiadavke:
```php index.php, riadky 18–22 $prefix = rtrim(dirname($_SERVER[‘SCRIPT_NAME’]), ‘/’); $path = parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH); $path = substr($path, strlen($prefix)); $path = ‘/’ . trim($path, ‘/’); define(‘BASE_URL’, $prefix);
Príklad pre požiadavku `GET /student/jan.novak/it/cv03/recipes/3?x=1`:
| Riadok | Hodnota | Poznámka |
|---|---|---|
| 1 | `$_SERVER['SCRIPT_NAME']` je `/student/jan.novak/it/cv03/index.php` | cesta k spustenému súboru; dal ju tam Apache (časť 2); je to vždy `index.php`, lebo tam smeruje `RewriteRule` |
| 1 | `dirname(…)` dá `/student/jan.novak/it/cv03`; `$prefix` je `/student/jan.novak/it/cv03` | `dirname` odstráni názov súboru; `rtrim(…, '/')` odstráni lomku na konci, ak tam je |
| 2 | `$_SERVER['REQUEST_URI']` je `/student/jan.novak/it/cv03/recipes/3?x=1` | cesta z prvého riadku požiadavky, aj s časťou za `?`; dal ju tam Apache |
| 2 | `$path` je `/student/jan.novak/it/cv03/recipes/3` | `parse_url(…, PHP_URL_PATH)` vráti len cestu; `?x=1` ostáva v `$_GET` |
| 3 | `$path` je `/recipes/3` | `substr` odreže toľko znakov od začiatku, koľko má prefix |
| 4 | `$path` je `/recipes/3` | `trim(…, '/')` odstráni lomky na oboch koncoch, `'/' .` pridá jednu na začiatok. Výsledok vždy začína `/` a nekončí `/`. Pre adresu `…/cv03/` vyjde `/`, pre `…/cv03/debug/` vyjde `/debug`. |
| 5 | konštanta `BASE_URL` je `/student/jan.novak/it/cv03` | **Konštanta** je pomenovaná hodnota, ktorú vytvorí `define('BASE_URL', $prefix)`. Od tejto chvíle je `BASE_URL` dostupná v každej funkcii a v každom súbore aplikácie bez parametra a jej hodnota sa už nezmení. Odtiaľ berie prefix funkcia `url()` (časť 6), ktorá ho pridáva do odkazov. |
Stránka `…/cv03/debug` v tvojom webovom priestore na sigma.tuke.sk vypíše všetkých päť hodnôt (`REQUEST_METHOD`, `SCRIPT_NAME`, `REQUEST_URI`, `$prefix`, `$path`) pre adresu, ktorú si práve zadal. Obrázok je v Ukážke 5.
### Router: trieda, ktorá vyberie stránku
**Router** je trieda `App\Router` v súbore `src/Router.php`. Má zoznam záznamov; každý záznam je dvojica *relatívna adresa* a *funkcia, ktorá pre túto adresu vráti HTML*. Jeden záznam v zozname sa volá **route**. Router má dve verejné metódy: `get()` pridá route do zoznamu, `dispatch()` nájde route pre relatívnu adresu z požiadavky a zavolá jej funkciu.
**Front controller** je `index.php`: jediný PHP súbor, ktorý Apache spúšťa (zabezpečuje to `RewriteRule`, časť 3). Ostatné súbory (`src/`, `views/`) sa spúšťajú tým, že ich `index.php` načíta.
V `index.php` je anonymná funkcia a konštanta:
- **Anonymná funkcia**: funkcia bez mena, napísaná priamo na mieste, kde sa odovzdáva: `function (): string { return 'text'; }`. Dá sa uložiť do premennej alebo poslať inej metóde ako parameter; tu ju posielaš metóde `get()`. Spustí sa až vtedy, keď ju niekto zavolá. Anonymná funkcia vidí len svoje parametre a premenné vo svojom tele; premennú z okolitého súboru jej dáš zápisom `use ($prefix, $path)` za zátvorkou s parametrami.
- **Konštanta** `BASE_URL`: vysvetlená v časti 4; tu sa vytvára na riadku 22.
#### index.php z router.zip
```php index.php
<?php
declare(strict_types=1);
// Konfigurácia ako prvá: zapne zobrazovanie chýb, aby bolo vidieť aj chybu v ďalších riadkoch.
$config = require __DIR__ . '/config.php';
if ($config['debug']) {
ini_set('display_errors', '1');
error_reporting(E_ALL);
}
// Jediný require: Composer nájde triedy v src/ (PSR-4) a načíta src/helpers.php ("files").
require __DIR__ . '/vendor/autoload.php';
use App\Router;
// Prefix a relatívna adresa.
// Požiadavka GET /student/jan.novak/it/cv03/recipes/3?x=1:
$prefix = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/'); // '/student/jan.novak/it/cv03'
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // '/student/jan.novak/it/cv03/recipes/3'
$path = substr($path, strlen($prefix)); // '/recipes/3'
$path = '/' . trim($path, '/'); // '/recipes/3' (pre '.../cv03/' vyjde '/')
define('BASE_URL', $prefix); // používa funkcia url()
// Zoznam route: relatívna adresa → funkcia, ktorá vráti HTML. Funkcie sa tu len ukladajú, nespúšťajú.
$router = new Router();
$router->get('/', function (): string {
return view('home', ['title' => 'Úvod']);
});
$router->get('/kontrola', function (): string {
return view('kontrola', ['title' => 'Kontrola projektu']);
});
$router->get('/debug', function () use ($prefix, $path): string {
return view('debug', ['title' => 'Debug', 'prefix' => $prefix, 'path' => $path]);
});
// Sem pridáš route pre svoje tabuľky (úlohy 4.3 a 4.4), napríklad:
// $router->get('/categories', function (): string {
// $model = new \App\Model\CategoryModel();
// return view('list', ['title' => $model->describe(), 'rows' => $model->getAll()]);
// });
// Spracovanie požiadavky – posledný riadok súboru: nájdi route, zavolaj funkciu, vypíš HTML.
echo $router->dispatch($_SERVER['REQUEST_METHOD'], $path);
| Riadok | Poznámka |
|---|---|
| 5–9 | z cv02: načíta config.php, zapne výpis chýb |
| 12 | z cv02: vendor/autoload.php. Od tohto riadku PHP nájde triedy v src/ a má načítané funkcie zo src/helpers.php (časť 7). |
| 14 | use: ďalej v súbore sa App\Router píše ako Router |
| 18–22 | prefix a relatívna adresa (časť 4); riadok 22 vytvorí konštantu BASE_URL s prefixom pre funkciu url() |
| 25 | vznikne objekt Router s prázdnym zoznamom route |
| 27–29 | route pre /: get() uloží do zoznamu dvojicu '/' a anonymnú funkciu z riadkov 27–29. Funkcia sa teraz nespúšťa, len sa uloží. Keď ju Router neskôr zavolá, vráti reťazec s HTML, ktorý vyrobí view() (časť 6). |
| 31–33 | route pre /kontrola: HTML kontrolnej stránky je vo views/kontrola.php |
| 35–37 | route pre /debug. use ($prefix, $path) sprístupní premenné z index.php vo vnútri funkcie. |
| 39–43 | miesto pre tvoje route; vzor je v komentári a celý v Ukážke 3 |
| 46 | jediné miesto, kde sa požiadavka spracuje. Je to posledný riadok súboru a spustí sa pri každej požiadavke. dispatch() dostane metódu (GET) a relatívnu adresu (/recipes/3), nájde route, zavolá jej funkciu a vráti HTML; echo ho pošle do tela odpovede. |
Poradie v súbore: najprv všetky get(), potom dispatch(). Route zapísaná za riadok 46 už v zozname nie je, keď dispatch() hľadá.
src/Router.php
<?php
declare(strict_types=1);
namespace App;
/**
* Router: zoznam dvojíc „relatívna adresa → funkcia, ktorá vráti HTML“ (route).
* get() pridá route do zoznamu, dispatch() nájde route pre adresu z požiadavky a zavolá jej funkciu.
*/
final class Router
{
/** @var array<int, array{method: string, pattern: string, handler: callable}> */
private array $routes = [];
/** Pridá route pre metódu GET. $path je relatívna adresa, napr. '/recipes/{id}'. */
public function get(string $path, callable $handler): void
{
$this->add('GET', $path, $handler);
}
private function add(string $method, string $path, callable $handler): void
{
// '/recipes/{id}' → '/recipes/(\d+)': {id} nahradí regulárny výraz pre číslo.
$pattern = preg_replace('#\{[a-z_]+\}#', '(\d+)', $path);
$this->routes[] = [
'method' => $method,
'pattern' => '#^' . $pattern . '$#',
'handler' => $handler,
];
}
/** Nájde route pre metódu a relatívnu adresu, zavolá jej funkciu a vráti jej HTML. Bez zhody vráti stránku 404. */
public function dispatch(string $method, string $path): string
{
foreach ($this->routes as $route) {
if ($route['method'] !== $method) {
continue;
}
if (preg_match($route['pattern'], $path, $m)) {
array_shift($m); // $m[0] je celá adresa, parametre sú od $m[1]
$params = array_map('intval', $m); // '3' → 3
return ($route['handler'])(...$params);
}
}
http_response_code(404);
return view('404', ['title' => 'Nenájdené']);
}
}
| Riadok | Poznámka |
|---|---|
| 4 | trieda je v namespace App, súbor je src/Router.php; autoloader ju nájde podľa pravidla App\ → src/ v composer.json |
| 10 | final: z triedy sa nededí; Router má jednu verziu pre celú aplikáciu |
| 12 | komentár /** @var … */ opisuje typ poľa pre editor (VS Code podľa neho napovedá); PHP ho ignoruje |
| 13 | zoznam route. Každá route je pole s tromi kľúčmi: metóda, vzor adresy, funkcia. callable je typ pre čokoľvek, čo sa dá zavolať; tu anonymná funkcia z index.php. |
| 16–19 | get(): metóda, ktorú voláš v index.php; uloží route pre metódu GET |
| 24 | z /recipes/{id} vyrobí /recipes/(\d+). {id} v adrese je parameter route. (\d+) je regulárny výraz: \d je cifra, + je jedna alebo viac, zátvorky si zhodu zapamätajú. |
| 27 | #^…$# je regulárny výraz pre celú adresu: ^ je začiatok, $ je koniec. Na /recipes/3 sedí, na /recipes/3/x nesedí. |
| 36–38 | route s inou metódou sa preskočí |
| 39 | preg_match porovná vzor s relatívnou adresou. Pri zhode dá do $m pole: $m[0] je celá adresa, $m[1] sú cifry zo zátvoriek (\d+). |
| 40–41 | $m[0] sa zahodí, zvyšok sa prevedie na čísla: $params je [3] |
| 42 | zavolá funkciu route s parametrami: ...$params rozloží pole [3] na jednotlivé parametre, pre /recipes/3 je to $handler(3). Návratová hodnota funkcie (HTML) je výsledok dispatch(). |
| 46–47 | žiadna route nesedí: http_response_code(404) povie Apache, aby do prvého riadku odpovede dal 404 Not Found (časť 2); návratová hodnota je HTML stránky „Nenájdené“ |
Cesta požiadavky GET …/cv03/recipes/3 cez celú aplikáciu je rozpísaná krok za krokom v časti „Ako to funguje: recept číslo 3 od adresy po stránku“.
Views a pomocné funkcie
View je PHP súbor v priečinku views/, ktorý obsahuje HTML jednej stránky a vypisuje hodnoty z premenných. Prácu s modelom a databázou robí funkcia route v index.php; view dostane hotové dáta a zobrazí ich.
Súbory vo views/:
| Súbor | Čo zobrazuje | Odkiaľ |
|---|---|---|
layout.php |
spoločný rám: <html>, <head>, menu, nadpis; obsah stránky sa vloží dovnútra |
router.zip |
home.php |
úvodná stránka | router.zip |
404.php |
text „Nenájdené“ a odkaz na úvod | router.zip |
debug.php |
tabuľka s piatimi hodnotami (časť 4) | router.zip |
kontrola.php |
kontrolná stránka z cv02 bez HTML rámu; do poľa $models doplníš svoje modely ako v cv02 |
router.zip |
list.php |
tabuľka záznamov | ty, úloha 4.3; vzor v Ukážke 4 |
show.php |
jeden záznam | ty, úloha 4.4; vzor v Ukážke 4 |
src/helpers.php
Súbor obsahuje tri funkcie: e(), url() a view(). Načíta sa pri každej požiadavke na riadku 12 index.php (ako, hovorí časť 7).
<?php
declare(strict_types=1);
// Funkcie e(), url() a view() pre views. Súbor načíta vendor/autoload.php pri každej požiadavke (composer.json → "files").
/** Ošetrí text pre výpis do HTML: znaky < > & " sa zobrazia ako znaky, nie ako HTML značky. */
function e(?string $text): string
{
return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8');
}
/** Z relatívnej adresy vyrobí plnú cestu pre href: url('/recipes/3') → '/student/jan.novak/it/cv03/recipes/3'. */
function url(string $path): string
{
return BASE_URL . '/' . ltrim($path, '/');
}
/** Vyrobí HTML stránky: načíta views/<name>.php, výsledok vloží do views/layout.php a vráti ako reťazec. */
function view(string $name, array $data = []): string
{
extract($data); // ['title' => 'Úvod'] → $title = 'Úvod'
ob_start(); // výstup view sa ukladá, do prehliadača sa neposiela
require __DIR__ . '/../views/' . $name . '.php';
$content = ob_get_clean(); // zachytený výstup ako reťazec
ob_start();
require __DIR__ . '/../views/layout.php'; // layout vypíše $content na svoje miesto
return ob_get_clean();
}
| Riadok | Poznámka |
|---|---|
| 1–4 | súbor nemá riadok namespace. Funkcie sú globálne: voláš ich e(), url(), view() z každého súboru bez use. |
| 7–10 | e(): skratka za htmlspecialchars(), ktoré bolo v cv02 v index.php pri každom výpise. Používaš ju pri každom výpise hodnoty z databázy do HTML. |
| 13–16 | url(): pred relatívnu adresu dá prefix z konštanty BASE_URL (index.php, riadok 22). V view píšeš <a href="<?= url('/recipes') ?>"> a odkaz vedie správne u teba aj u učiteľa. |
| 19 | $name je názov view bez .php; $data sú hodnoty pre view |
| 21 | extract(['title' => 'Úvod']) vytvorí premennú $title s hodnotou 'Úvod'. Preto view môže písať <?= e($title) ?>. |
| 23–25 | ob_start() zapne zachytávanie výstupu: všetko, čo view vypíše, sa neposiela do prehliadača, ale ukladá. require spustí view. ob_get_clean() vráti zachytený výstup ako reťazec a zachytávanie vypne. $content je HTML obsahu stránky. |
| 27–29 | to isté s layout.php. Layout má v sebe <?= $content ?> (riadok 23 v layout.php), takže výsledok je celá stránka ako jeden reťazec. Ten vráti funkcia route, ten vráti dispatch(), ten vypíše echo v index.php na riadku 46. |
views/layout.php
<!doctype html>
<html lang="sk">
<head>
<meta charset="utf-8">
<title><?= e($title) ?></title>
<style>
body { font-family: system-ui, sans-serif; max-width: 60rem; margin: 2rem auto; padding: 0 1rem; }
nav a { margin-right: 1rem; }
table { border-collapse: collapse; margin-bottom: 2rem; }
th, td { border: 1px solid #999; padding: .3rem .6rem; text-align: left; }
th { background: #eee; }
dt { font-weight: bold; margin-top: .6rem; }
</style>
</head>
<body>
<nav>
<a href="<?= url('/') ?>">Úvod</a>
<a href="<?= url('/kontrola') ?>">Kontrola</a>
<a href="<?= url('/debug') ?>">Debug</a>
</nav>
<h1><?= e($title) ?></h1>
<?= $content ?>
</body>
</html>
| Riadok | Poznámka |
|---|---|
| 5, 21 | $title prišiel cez view('home', ['title' => 'Úvod']) a extract() |
| 16–20 | menu. Každý odkaz je cez url(), prefix nie je napísaný nikde. V úlohe 4.3 sem pridáš odkaz pre každú svoju tabuľku. |
| 23 | sem sa vloží HTML view ($content z view()). Bez e(), lebo $content je hotové HTML. |
views/debug.php a views/404.php
<table>
<tr><th>$_SERVER['REQUEST_METHOD']</th><td><?= e($_SERVER['REQUEST_METHOD']) ?></td></tr>
<tr><th>$_SERVER['SCRIPT_NAME']</th><td><?= e($_SERVER['SCRIPT_NAME']) ?></td></tr>
<tr><th>$_SERVER['REQUEST_URI']</th><td><?= e($_SERVER['REQUEST_URI']) ?></td></tr>
<tr><th>$prefix</th><td><?= e($prefix) ?></td></tr>
<tr><th>$path (relatívna adresa)</th><td><?= e($path) ?></td></tr>
</table>
<p>Zmeň koniec adresy v riadku s adresou na <code>/debug/</code>, <code>/debug?x=1</code> alebo <code>/Debug</code> a sleduj, čo sa v tabuľke zmení.</p>
| Riadok | Poznámka |
|---|---|
| 2–4 | hodnoty, ktoré do PHP dal Apache z požiadavky |
| 5–6 | hodnoty, ktoré vypočítal index.php na riadkoch 18–21; prišli cez view('debug', ['prefix' => $prefix, 'path' => $path]) |
| 8 | /debug/ dá rovnaký $path (riadok 21 index.php odstráni lomku); /Debug dá stránku 404 (vzor route rozlišuje veľké a malé písmená) |
<p>Pre túto adresu aplikácia nemá stránku (stavový kód 404).</p>
<p><a href="<?= url('/') ?>">Späť na úvod</a></p>
Stránku 404 vráti Router::dispatch() (riadok 47 Router.php) pre adresu bez route a funkcia route pre /recipes/{id} pre id, ktoré v tabuľke nie je (Ukážka 3).
views/kontrola.php
Kontrolná stránka z cv02 bez častí, ktoré teraz robí index.php (konfigurácia, autoload) a layout.php (<html>, <head>, <h1>, </html>). Ostal kód, ktorý číta tabuľky a modely, a HTML od <h2> ďalej. htmlspecialchars() je nahradené e(). Do poľa $models doplníš svoje modely rovnako ako v cv02.
```php views/kontrola.php, riadky 1–15 query(‘SHOW TABLES’)->fetchAll(PDO::FETCH_COLUMN);
// 2. Tvoje modely – jeden riadok pre každú triedu: $models = [ // new (), // new (),]; ?>
| Riadok | Poznámka |
|---|---|
| 3 | `use` funguje aj v view: view je PHP súbor načítaný cez `require` vo `view()` |
| 11–14 | sem napíš `new \App\Model\TvojModel(),` pre každú svoju triedu (úloha 4.2) |
### Composer: blok "files" v composer.json
V `composer.json` v časti `"autoload"` sú dva kľúče. `"psr-4"` z cv02 hovorí Composeru: trieda `App\X` je v súbore `src/X.php`; súbor sa načíta vo chvíli, keď kód použije triedu `App\X` (napríklad `new Router()` načíta `src/Router.php`). `"files"` hovorí Composeru: tieto súbory načítaj hneď pri `require vendor/autoload.php`.
`src/helpers.php` je v `"files"`. Obsahuje funkcie `e()`, `url()` a `view()`, a tie sú vďaka tomu dostupné od riadku 12 `index.php` v každom súbore aplikácie.
```json composer.json
{
"name": "tuke/it-projekt",
"description": "Semestrálny projekt – Informačné technológie",
"type": "project",
"require": {
"php": ">=8.1"
},
"autoload": {
"psr-4": {
"App\\": "src/"
},
"files": [
"src/helpers.php"
]
},
"config": {
"platform": {
"php": "8.1.2"
}
}
}
| Riadok | Poznámka |
|---|---|
| 9–11 | z cv02: triedy App\… sú v src/ |
| 12–14 | nové: zoznam súborov, ktoré vendor/autoload.php načíta pri každej požiadavke. Cesta je relatívna k composer.json. |
Kedy a kde: po zmene composer.json spustíš v termináli v Kubeflow v priečinku ~/web/it/cv03 príkaz composer install. Composer vytvorí vendor/ a v ňom súbor vendor/composer/autoload_files.php so záznamom o src/helpers.php. Potom pravý klik na cv03 → Upload Folder, aby bol vendor/ aj na sigma.tuke.sk.
Ako overíš: otvor …/cv03/. Zobrazí sa úvodná stránka s menu. Ak sa zobrazí Fatal error: Call to undefined function view(), vendor/ na sigma.tuke.sk je z cv02 bez záznamu o helpers.php: spusti composer install a nahraj vendor/ znova cez Upload Folder.
Viac: Composer: autoload files
Ako to funguje: recept číslo 3 od adresy po stránku
Čo Ján Novák chce: otvoriť recept číslo 3. Klikne v zozname receptov na číslo 3, alebo napíše https://sigma.tuke.sk/student/jan.novak/it/cv03/recipes/3 a stlačí Enter. Ideme po poradí, krok za krokom.
Krok 1. Prehliadač pošle požiadavku.
GET /student/jan.novak/it/cv03/recipes/3 HTTP/1.1
Host: sigma.tuke.sk
Krok 2. Apache na sigma.tuke.sk hľadá súbor a riadi sa .htaccess. Súbor public_html/it/cv03/recipes/3 na disku nie je. V .htaccess platí:
RewriteCond %{REQUEST_FILENAME} !-f # súbor "recipes/3" neexistuje → podmienka platí
RewriteRule ^ index.php [L] # → Apache spustí index.php
Pred spustením Apache naplní pole $_SERVER:
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/student/jan.novak/it/cv03/recipes/3';
$_SERVER['SCRIPT_NAME'] = '/student/jan.novak/it/cv03/index.php';
Krok 3. Beží index.php. Riadky, ktoré sa pri tejto požiadavke vykonajú, s hodnotami v komentároch:
$config = require __DIR__ . '/config.php'; // pole s údajmi k databáze; debug je true
require __DIR__ . '/vendor/autoload.php'; // od teraz PHP nájde triedy App\... a má e(), url(), view()
$prefix = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/'); // '/student/jan.novak/it/cv03'
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // '/student/jan.novak/it/cv03/recipes/3'
$path = substr($path, strlen($prefix)); // '/recipes/3'
$path = '/' . trim($path, '/'); // '/recipes/3'
define('BASE_URL', $prefix); // pre funkciu url()
$router = new Router(); // prázdny zoznam route
$router->get('/', ...); // route sa len ukladajú, funkcie sa nespúšťajú
$router->get('/recipes', ...);
$router->get('/recipes/{id}', function (int $id): string { // route pre náš detail (Ukážka 3)
$model = new \App\Model\RecipeModel();
$row = $model->getById($id);
if ($row === null) {
http_response_code(404);
return view('404', ['title' => 'Nenájdené']);
}
return view('show', ['title' => $row['title'], 'row' => $row, 'back' => '/recipes']);
});
echo $router->dispatch($_SERVER['REQUEST_METHOD'], $path); // dispatch('GET', '/recipes/3') – krok 4
Krok 4. Router::dispatch('GET', '/recipes/3') hľadá route. V src/Router.php prebehne zoznam. Pri route /recipes/{id}, ktorej vzor je po add() text #^/recipes/(\d+)$#:
if (preg_match('#^/recipes/(\d+)$#', '/recipes/3', $m)) { // sedí; (\d+) zachytilo '3'
array_shift($m); // $m bolo ['/recipes/3', '3'], teraz ['3']
$params = array_map('intval', $m); // [3] – text '3' → číslo 3
return ($route['handler'])(...$params); // zavolá funkciu route s $id = 3
}
Krok 5. Funkcia route pre /recipes/{id} beží s $id = 3. new RecipeModel() vytvorí model (jeho konštruktor si cez Database::getInstance() vezme pripojenie k databáze). getById(3) pošle dotaz SELECT r.*, d.name AS difficulty_name FROM recipes r JOIN difficulties d ON d.id = r.difficulty_id WHERE r.id = 3 a vráti jeden záznam ako pole: ['id' => 3, 'title' => '…', 'servings' => 4, …, 'difficulty_name' => 'ľahký']. Záznam existuje, preto sa volá view('show', […]).
Krok 6. view() vyrobí HTML. V src/helpers.php:
function view(string $name, array $data = []): string
{
extract($data); // $title, $row, $back
ob_start(); // výpis sa zachytáva, nejde do prehliadača
require __DIR__ . '/../views/' . $name . '.php'; // spustí views/show.php → <dl>...</dl>
$content = ob_get_clean(); // $content = '<dl>...</dl><p><a ...>Späť na zoznam</a></p>'
ob_start();
require __DIR__ . '/../views/layout.php'; // layout vloží $content do rámu stránky
return ob_get_clean(); // '<!doctype html>...celá stránka...</html>'
}
HTML celej stránky sa vráti z view() do funkcie route, z funkcie route do dispatch(), z dispatch() do index.php.
Krok 7. echo v index.php vypíše HTML. Apache dopíše prvý riadok HTTP/1.1 200 OK (PHP nezavolalo http_response_code(), preto 200) a hlavičky, a odpoveď pošle prehliadaču. Prehliadač zobrazí menu, nadpis s názvom receptu a záznam ako zoznam dvojíc stĺpec–hodnota.
Pre …/cv03/recipes/999 je všetko rovnaké až po getById(999), ktoré vráti null: funkcia route zavolá http_response_code(404) (Apache dá do prvého riadku 404 Not Found) a vráti view('404', …). Pre …/cv03/nic nesedí žiadna route a stránku 404 vráti sám dispatch() (riadky 46–47 Router.php).
Najčastejšie chyby a čo znamenajú
| Čo vidíš | Príčina | Riešenie |
|---|---|---|
stránka Apache „Not Found“ bez menu aplikácie pre …/cv03/debug |
.htaccess na sigma.tuke.sk chýba alebo nemá riadky 13–15 |
ulož .htaccess z router.zip, Upload Folder |
| stavový kód 500 na každej adrese | preklep v .htaccess |
porovnaj so súborom v časti 3 riadok po riadku |
Call to undefined function view() |
vendor/ na sigma.tuke.sk nemá záznam o helpers.php |
composer install v Kubeflow, Upload Folder |
Class "App\Router" not found |
src/Router.php chýba na sigma.tuke.sk |
Upload Folder |
| tvoja stránka 404 pre adresu, ktorá má route | route je zapísaná za riadkom echo $router->dispatch(…), alebo adresa v get() má preklep |
presuň get() pred dispatch(); porovnaj adresu v get() s $path na stránke /debug |
odkaz z menu vedie na sigma.tuke.sk/recipes |
v view je href="/recipes" namiesto url('/recipes') |
použi url() |
/recipes/abc dá stránku 404 |
správne správanie: (\d+) sedí len na cifry |
nič |
/debug ukazuje $path ako /index.php/debug |
v adrese je index.php: …/cv03/index.php/debug |
adresu píš bez index.php |
Failed opening required '…/views/list.php' |
view s týmto názvom vo views/ nie je, alebo má iný názov než vo view('list', …) |
názov súboru bez .php = prvý parameter view() |
What you get today and what you do with it
The starting point is the cv02 repository: the check page works, the models are in src/Model/, the database has data. The result is the cv03 repository, in which the application answers these addresses (categories and recipes are names from the sample application; in yours they are the names of your tables):
| Address in the browser | What is shown | Part |
|---|---|---|
https://sigma.tuke.sk/student/meno.priezvisko/it/cv03/ |
home page | 5 |
…/it/cv03/kontrola |
check page from cv02 | 6 |
…/it/cv03/categories |
table of records of a lookup table | Example 3 |
…/it/cv03/recipes |
table of records of the main entity, id is a link to the detail |
Example 3 |
…/it/cv03/recipes/3 |
one record of the main entity with id 3 |
Example 3 |
…/it/cv03/debug |
helper page: what arrived at the server and what the application computed from it | 4 |
…/it/cv03/anything-else |
“Not found” page with status code 404 (part 2) | 2, 5 |
You download router.zip from the course website (by clicking, or with the curl command in task 4.1). It has 10 files:
.htaccess replaces .htaccess from cv02: 3 lines added (part 3)
composer.json replaces composer.json from cv02: "files" block added (part 7)
index.php replaces index.php from cv02: new content (part 5)
src/Router.php new: the Router class (part 5)
src/helpers.php new: functions e(), url(), view() (part 6)
views/layout.php new: shared HTML frame of every page (part 6)
views/home.php new: content of the home page (part 6)
views/404.php new: content of the "Not found" page (part 6)
views/debug.php new: content of the helper page (part 4)
views/kontrola.php new: check page from cv02 without the HTML frame; you add your models (part 6)
The procedure is in task 4.1. In short: clone the cv03 repository into ~/web/it/cv03, copy the unchanged files from cv02 into it, unzip router.zip, run composer install and upload the folder to sigma.tuke.sk.
From cv02 you copy these files and folders (only the files in router.zip change):
cd ~/web/it
cp cv02/config.php cv03/
cp cv02/config.example.php cv03/
cp cv02/.gitignore cv03/
cp -r cv02/sql cv03/
cp -r cv02/src cv03/
| Line | Note |
|---|---|
| 1 | the folder where cv02 and cv03 sit side by side |
| 2 | database credentials; the same, it is the same database |
| 3–4 | configuration template and the list for Git; unchanged |
| 5 | schema.sql and seed.sql; -r copies a folder with its contents |
| 6 | Database.php and Model/ with your models; router.zip adds Router.php and helpers.php to src/ |
From cv02 you do not copy:
| File / folder | Why |
|---|---|
.git/ |
history of the cv02 repository; cv03 has its own history, which started at clone |
vendor/ |
result of the composer install command; you create it again in cv03, because composer.json changed |
.htaccess, composer.json, index.php |
the new version is in router.zip |
README.md |
cv03 has its own with this week’s tasks |
Where things are after task 4.1:
| File | Kubeflow ~/web/it/cv03 |
sigma.tuke.sk public_html/it/cv03 |
GitHub cv03-login |
|---|---|---|---|
index.php, .htaccess, composer.json, src/, views/, sql/ |
yes | yes (save in the editor, Upload Folder) | yes |
config.php |
yes | yes (save in the editor) | no (.gitignore) |
vendor/ |
yes (composer install) |
yes (Upload Folder) | no (.gitignore) |
HTTP: request and response
HTTP is the set of rules by which the browser and the server talk. The conversation always has two steps: the browser sends a request, the server returns a response. One request, one response.
Where the request originates: in the browser. You type an address into the address bar and press Enter, or click a link, or submit a form. The browser builds the text of the request and sends it to the server sigma.tuke.sk.
Who writes the request: the browser. You type the address, the browser splits it into lines and sends them. Nobody writes this by hand and you do not see it in the browser window; the browser shows it only in the Network tab (end of this part).
What is in the request. You type https://sigma.tuke.sk/student/meno.priezvisko/it/cv03/recipes/3, the browser builds this text from the address and sends it (first three lines):
GET /student/meno.priezvisko/it/cv03/recipes/3 HTTP/1.1
Host: sigma.tuke.sk
Accept: text/html
| Line | Note |
|---|---|
| 1 | GET is the method of the request: the kind of request. After it is the path: the part of the address after the server name. The whole application works with the path today. |
| 2 | the name of the server the request is for |
| 3 | what the browser wants to receive; for pages always HTML |
Which part of the address goes into which line:
| Part of the address | Where the browser puts it |
|---|---|
https:// |
nowhere; it only says the transfer is encrypted |
sigma.tuke.sk |
line 2, Host:; everything between // and the first slash |
/student/meno.priezvisko/it/cv03/recipes/3 |
line 1, the path; everything from the first slash to the end (without the part after ?) |
the word GET |
line 1, the method; the browser puts it there because you typed the address or clicked a link; when a form with method="post" is submitted it puts POST |
HTTP/1.1, Accept: text/html |
end of line 1 and line 3; fixed in the browser |
Every file is a separate request: the page is one request, every image and every CSS file in it is another request. That is why the Network tab has several rows for one page.
Request methods you work with in this course:
| Method | When the browser sends it | Where the data is |
|---|---|---|
GET |
address + Enter, click on a link, form with method="get" |
in the address after ?: ?q=abc is $_GET['q'] in PHP |
POST |
form with method="post" |
in the request body, $_POST in PHP |
PUT, DELETE |
the browser does not send them from a page by itself; a program sends them (JavaScript, another application) | in the request body |
Today you work only with GET.
$_SERVER is an array Apache fills for PHP on every request, just like $_GET and $_POST. From the request lines it holds: the method in $_SERVER['REQUEST_METHOD'] (GET), the path in $_SERVER['REQUEST_URI'] (/student/meno.priezvisko/it/cv03/recipes/3), the server in $_SERVER['HTTP_HOST'] (sigma.tuke.sk). Apache also adds the path of the file it ran: $_SERVER['SCRIPT_NAME'] (part 4).
Where the request arrives: at the server sigma.tuke.sk, in the Apache program. Apache picks a file in your web space (public_html/it/cv03/…) according to the path, runs a .php file, and sends everything PHP outputs (echo, HTML after ?>) back as the response.
Who writes the response: two parties. PHP writes the body (everything echo prints and the HTML after ?>). The first line and the headers are added by Apache itself; it puts 200 OK in the first line unless PHP said otherwise. PHP says otherwise by calling http_response_code(404): from then on Apache puts 404 Not Found in the first line.
What is in the response:
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
<!doctype html>
<html lang="sk">
| Line | Note |
|---|---|
| 1 | status code: a number that says how the request went |
| 2 | type of the content in the body |
| 4–5 | the body of the response: what PHP output; the browser displays it |
Status codes you use today:
| Code | Meaning | When your application sends it |
|---|---|---|
200 OK |
the page exists, here it is | every page found; Apache adds it, you write nothing |
404 Not Found |
I have no page for this path | a path for which the Router has no entry; written by the line http_response_code(404); in Router::dispatch() (part 5) |
500 Internal Server Error |
PHP ended with an error | an error in the code; you see the error text because config.php has 'debug' => true |
Where the response arrives: back in the browser. The body is shown in the window. The first line and the headers are not shown, but the browser can display them: press F12, click the Network tab, reload the page (F5), click the first row in the list, on the right the Headers tab. At the top is Status Code, below it Request Headers (the request) and Response Headers (the response). The picture is in Example 1.
More: MDN: HTTP overview
.htaccess: rewriting paths
.htaccess is a text file named exactly .htaccess (dot at the start, no extension), stored in a folder on the server. Apache reads it on every request aimed at this folder or its subfolders and follows the commands in it. A command in .htaccess is called a directive: one line, the first word is the directive name, then its parameters.
Where it is: in the root of the application, next to index.php: ~/web/it/cv03/.htaccess in Kubeflow, public_html/it/cv03/.htaccess on sigma.tuke.sk, in the repository on GitHub. The name starts with a dot, Linux treats it as hidden: ls -a shows it in the terminal, Explorer in VS Code shows it greyed, WinSCP shows it only with hidden files switched on.
When it is used: on every request, without a restart and without running anything. You save the file in the editor (SFTP transfers it to sigma.tuke.sk) and the next request already follows the new content. A typo in a directive name means every request into the folder gets status code 500. The fix is fixing the line and saving.
What can be set in .htaccess:
| Group of directives | Example | For | Here |
|---|---|---|---|
| access to files | Require all denied |
the file cannot be opened from the browser | config.php (cv02) |
| response for a path pattern | RedirectMatch 404 … |
return a status code for paths matching the pattern | src, vendor, sql, .git (cv02) |
| folder listing | IndexIgnore * |
a folder without index.php does not list its contents |
cv02 |
| rewriting paths | RewriteRule |
serve a request for one path with another file | today |
| error pages | ErrorDocument 404 /error.html |
own file for a status code | no; the Router makes the 404 page |
| password on a folder | AuthType Basic + Require valid-user |
folder protected by name and password | no |
| PHP settings | php_value upload_max_filesize 8M |
change a PHP setting for this folder | no |
On sigma.tuke.sk all groups from the table are allowed in .htaccess.
The whole .htaccess for cv03 (lines 1–10 are from cv02, lines 12–15 are new):
# Folders with code and SQL are not pages.
RedirectMatch 404 /(src|vendor|sql|\.git)(/|$)
# The file with the database password cannot be opened over the web.
<Files "config.php">
Require all denied
</Files>
# A folder without index.php does not list its contents.
IndexIgnore *
# Rewriting paths: every path that is not an existing file goes to index.php.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
| Line | Note |
|---|---|
| 2, 5–7, 10 | from cv02, explained in week 3 |
| 13 | switches on the Apache module for rewriting paths (mod_rewrite). Without this line Apache ignores lines 14 and 15. |
| 14 | condition for the following RewriteRule. %{REQUEST_FILENAME} is the file on disk that corresponds to the path of the request. !-f means “it is not an existing file”. For /recipes/3 the condition holds (there is no file recipes/3 in the folder). For /css/style.css it does not hold (the file exists). |
| 15 | rule: if the condition holds, serve the request with the file index.php. ^ matches every path. [L] means last rule, no further rules are searched. |
What happens with a concrete request:
| Browser asks for | Does the file exist? | Apache runs |
|---|---|---|
…/cv03/recipes/3 |
no | index.php; the original path /…/cv03/recipes/3 stays in $_SERVER['REQUEST_URI'] (part 4) |
…/cv03/css/style.css |
yes | sends css/style.css; index.php does not run |
…/cv03/ |
a folder; Apache looks for index.php in it |
index.php |
…/cv03/src/Router.php |
yes, but line 2 applies first | response 404 |
How you verify that lines 13–15 work: open …/cv03/debug. A table with five rows appears (part 4): rewriting runs. The Apache “Not Found” page without your application’s menu appears: rewriting does not run; check that .htaccess is on sigma.tuke.sk and has the line RewriteEngine On.
More: Apache: mod_rewrite
Prefix and relative address
The prefix is the part of the path that is the same in all addresses of your application: /student/meno.priezvisko/it/cv03. It differs for every student; for the teacher it is /beata.stehlikova/it/ukazky/cv03.
The relative address is the path without the prefix: /, /recipes, /recipes/3. The Router (part 5) works only with the relative address. That is why the same index.php is correct for every student and for the teacher.
Four lines in index.php produce the relative address, a fifth stores the prefix. They are lines 18–22 of index.php (part 5) and run on every request:
```php index.php, lines 18–22 $prefix = rtrim(dirname($_SERVER[‘SCRIPT_NAME’]), ‘/’); $path = parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH); $path = substr($path, strlen($prefix)); $path = ‘/’ . trim($path, ‘/’); define(‘BASE_URL’, $prefix);
Example for the request `GET /student/jan.novak/it/cv03/recipes/3?x=1`:
| Line | Value | Note |
|---|---|---|
| 1 | `$_SERVER['SCRIPT_NAME']` is `/student/jan.novak/it/cv03/index.php` | path to the file that runs; Apache put it there (part 2); always `index.php`, because `RewriteRule` points there |
| 1 | `dirname(…)` gives `/student/jan.novak/it/cv03`; `$prefix` is `/student/jan.novak/it/cv03` | `dirname` removes the file name; `rtrim(…, '/')` removes a trailing slash if there is one |
| 2 | `$_SERVER['REQUEST_URI']` is `/student/jan.novak/it/cv03/recipes/3?x=1` | the path from the first line of the request, including the part after `?`; Apache put it there |
| 2 | `$path` is `/student/jan.novak/it/cv03/recipes/3` | `parse_url(…, PHP_URL_PATH)` returns only the path; `?x=1` stays in `$_GET` |
| 3 | `$path` is `/recipes/3` | `substr` cuts off as many characters from the start as the prefix has |
| 4 | `$path` is `/recipes/3` | `trim(…, '/')` removes slashes at both ends, `'/' .` adds one at the start. The result always starts with `/` and does not end with `/`. For the address `…/cv03/` it gives `/`, for `…/cv03/debug/` it gives `/debug`. |
| 5 | the constant `BASE_URL` is `/student/jan.novak/it/cv03` | the prefix for the function `url()` (part 6), which adds it to links |
The page `…/cv03/debug` in your web space on sigma.tuke.sk prints all five values (`REQUEST_METHOD`, `SCRIPT_NAME`, `REQUEST_URI`, `$prefix`, `$path`) for the address you just typed. The picture is in Example 5.
### Router: the class that picks the page
The **Router** is the class `App\Router` in the file `src/Router.php`. It has a list of entries; each entry is a pair of a *relative address* and a *function that returns the HTML for this address*. One entry in the list is called a **route**. The Router has two public methods: `get()` adds a route to the list, `dispatch()` finds the route for the relative address of the request and calls its function.
The **front controller** is `index.php`: the only PHP file Apache runs (the `RewriteRule` in part 3 ensures that). The other files (`src/`, `views/`) run because `index.php` loads them.
`index.php` uses two things from PHP that were not in OOP:
- **Anonymous function**: a function without a name, written right where it is passed on: `function (): string { return 'text'; }`. It can be stored in a variable or passed to another method as a parameter; here you pass it to the method `get()`. It runs only when someone calls it. An anonymous function sees only its parameters and the variables in its body; you give it a variable from the surrounding file with `use ($prefix, $path)` after the parameter parentheses.
- **Constant**: a named value created by `define('BASE_URL', $prefix)`. From then on `BASE_URL` is available in every function and every file of the application without `use` and without a parameter, and its value does not change any more. That is why the prefix is in a constant and the function `url()` (part 6) has somewhere to take it from.
#### index.php from router.zip
```php index.php
<?php
declare(strict_types=1);
// Configuration first: switches error display on, so an error in the next lines is visible too.
$config = require __DIR__ . '/config.php';
if ($config['debug']) {
ini_set('display_errors', '1');
error_reporting(E_ALL);
}
// The only require: Composer finds classes in src/ (PSR-4) and loads src/helpers.php ("files").
require __DIR__ . '/vendor/autoload.php';
use App\Router;
// Prefix and relative address.
// Request GET /student/jan.novak/it/cv03/recipes/3?x=1:
$prefix = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/'); // '/student/jan.novak/it/cv03'
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // '/student/jan.novak/it/cv03/recipes/3'
$path = substr($path, strlen($prefix)); // '/recipes/3'
$path = '/' . trim($path, '/'); // '/recipes/3' (for '.../cv03/' gives '/')
define('BASE_URL', $prefix); // used by the function url()
// List of routes: relative address → function that returns HTML. Functions are only stored here, not run.
$router = new Router();
$router->get('/', function (): string {
return view('home', ['title' => 'Úvod']);
});
$router->get('/kontrola', function (): string {
return view('kontrola', ['title' => 'Kontrola projektu']);
});
$router->get('/debug', function () use ($prefix, $path): string {
return view('debug', ['title' => 'Debug', 'prefix' => $prefix, 'path' => $path]);
});
// Here you add routes for your tables (tasks 4.3 and 4.4), for example:
// $router->get('/categories', function (): string {
// $model = new \App\Model\CategoryModel();
// return view('list', ['title' => $model->describe(), 'rows' => $model->getAll()]);
// });
// Processing the request – the last line of the file: find the route, call the function, print the HTML.
echo $router->dispatch($_SERVER['REQUEST_METHOD'], $path);
| Line | Note |
|---|---|
| 5–9 | from cv02: loads config.php, switches error display on |
| 12 | from cv02: vendor/autoload.php. From this line PHP finds classes in src/ and has the functions from src/helpers.php loaded (part 7). |
| 14 | use: further in the file App\Router is written as Router |
| 18–22 | prefix and relative address (part 4); line 22 creates the constant BASE_URL with the prefix for the function url() |
| 25 | a Router object with an empty list of routes is created |
| 27–29 | route for /: get() stores the pair '/' and the anonymous function from lines 27–29 in the list. The function is not run now, only stored. When the Router calls it later, it returns a string with HTML made by view() (part 6). |
| 31–33 | route for /kontrola: the HTML of the check page is in views/kontrola.php |
| 35–37 | route for /debug. use ($prefix, $path) makes the variables from index.php available inside the function. |
| 39–43 | the place for your routes; the pattern is in the comment and in full in Example 3 |
| 46 | the only place where the request is processed. It is the last line of the file and runs on every request. dispatch() receives the method (GET) and the relative address (/recipes/3), finds the route, calls its function and returns HTML; echo sends it into the response body. |
Order in the file: first all get(), then dispatch(). A route written after line 46 is not in the list yet when dispatch() searches.
src/Router.php
<?php
declare(strict_types=1);
namespace App;
/**
* Router: list of pairs "relative address → function that returns HTML" (routes).
* get() adds a route to the list, dispatch() finds the route for the request's address and calls its function.
*/
final class Router
{
/** @var array<int, array{method: string, pattern: string, handler: callable}> */
private array $routes = [];
/** Adds a route for the GET method. $path is a relative address, e.g. '/recipes/{id}'. */
public function get(string $path, callable $handler): void
{
$this->add('GET', $path, $handler);
}
private function add(string $method, string $path, callable $handler): void
{
// '/recipes/{id}' → '/recipes/(\d+)': {id} is replaced by a regular expression for a number.
$pattern = preg_replace('#\{[a-z_]+\}#', '(\d+)', $path);
$this->routes[] = [
'method' => $method,
'pattern' => '#^' . $pattern . '$#',
'handler' => $handler,
];
}
/** Finds the route for the method and relative address, calls its function and returns its HTML. No match: the 404 page. */
public function dispatch(string $method, string $path): string
{
foreach ($this->routes as $route) {
if ($route['method'] !== $method) {
continue;
}
if (preg_match($route['pattern'], $path, $m)) {
array_shift($m); // $m[0] is the whole address, parameters start at $m[1]
$params = array_map('intval', $m); // '3' → 3
return ($route['handler'])(...$params);
}
}
http_response_code(404);
return view('404', ['title' => 'Nenájdené']);
}
}
| Line | Note |
|---|---|
| 4 | the class is in the namespace App, the file is src/Router.php; Composer finds it by PSR-4 (week 3) |
| 10 | final: nothing inherits from the class; the Router has one version for the whole application |
| 12 | the comment /** @var … */ describes the array type for the editor (VS Code uses it for hints); PHP ignores it |
| 13 | the list of routes. Each route is an array with three keys: method, address pattern, function. callable is the type for anything that can be called; here the anonymous function from index.php. |
| 16–19 | get(): the method you call in index.php; stores a route for the GET method |
| 24 | makes /recipes/(\d+) out of /recipes/{id}. {id} in the address is a route parameter. (\d+) is a regular expression: \d is a digit, + is one or more, the parentheses remember the match. |
| 27 | #^…$# is a regular expression for the whole address: ^ is the start, $ is the end. It matches /recipes/3, it does not match /recipes/3/x. |
| 36–38 | a route with another method is skipped |
| 39 | preg_match compares the pattern with the relative address. On a match it fills $m: $m[0] is the whole address, $m[1] the digits from the parentheses (\d+). |
| 40–41 | $m[0] is dropped, the rest converted to numbers: $params is [3] |
| 42 | calls the route’s function with the parameters: ...$params unpacks the array [3] into separate parameters, for /recipes/3 it is $handler(3). The function’s return value (HTML) is the result of dispatch(). |
| 46–47 | no route matches: http_response_code(404) tells Apache to put 404 Not Found in the first line of the response (part 2); the return value is the HTML of the “Not found” page |
The path of the request GET …/cv03/recipes/3 through the whole application is written out step by step in the part “How it works: recipe number 3 from the address to the page”.
Views and helper functions
A view is a PHP file in the views/ folder that contains the HTML of one page and prints values from variables. The work with the model and the database is done by the route’s function in index.php; the view receives ready data and displays it.
Files in views/:
| File | What it shows | From |
|---|---|---|
layout.php |
shared frame: <html>, <head>, menu, heading; the page content is inserted inside |
router.zip |
home.php |
home page | router.zip |
404.php |
the text “Not found” and a link to the home page | router.zip |
debug.php |
table with five values (part 4) | router.zip |
kontrola.php |
check page from cv02 without the HTML frame; you add your models to the $models array as in cv02 |
router.zip |
list.php |
table of records | you, task 4.3; pattern in Example 4 |
show.php |
one record | you, task 4.4; pattern in Example 4 |
src/helpers.php
The file contains three functions: e(), url() and view(). It is loaded on every request on line 12 of index.php (part 7 says how).
<?php
declare(strict_types=1);
// Three functions for views. vendor/autoload.php loads the file on every request (composer.json → "files").
/** Prepares text for output into HTML: the characters < > & " are shown as characters, not as HTML tags. */
function e(?string $text): string
{
return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8');
}
/** Makes a full path for href from a relative address: url('/recipes/3') → '/student/jan.novak/it/cv03/recipes/3'. */
function url(string $path): string
{
return BASE_URL . '/' . ltrim($path, '/');
}
/** Makes the HTML of a page: loads views/<name>.php, inserts the result into views/layout.php and returns it as a string. */
function view(string $name, array $data = []): string
{
extract($data); // ['title' => 'Úvod'] → $title = 'Úvod'
ob_start(); // the view's output is stored, not sent to the browser
require __DIR__ . '/../views/' . $name . '.php';
$content = ob_get_clean(); // the stored output as a string
ob_start();
require __DIR__ . '/../views/layout.php'; // the layout prints $content in its place
return ob_get_clean();
}
| Line | Note |
|---|---|
| 1–4 | the file has no namespace line. The functions are global: you call them e(), url(), view() from every file without use. |
| 7–10 | e(): a short name for htmlspecialchars(), which was in index.php in cv02 at every output. You use it at every output of a value from the database into HTML. |
| 13–16 | url(): puts the prefix from the constant BASE_URL (index.php, line 22) before the relative address. In a view you write <a href="<?= url('/recipes') ?>"> and the link leads correctly for you and for the teacher. |
| 19 | $name is the view name without .php; $data are the values for the view |
| 21 | extract(['title' => 'Úvod']) creates the variable $title with the value 'Úvod'. That is why a view can write <?= e($title) ?>. |
| 23–25 | ob_start() switches output capturing on: everything the view prints is not sent to the browser but stored. require runs the view. ob_get_clean() returns the stored output as a string and switches capturing off. $content is the HTML of the page content. |
| 27–29 | the same with layout.php. The layout contains <?= $content ?> (line 23 of layout.php), so the result is the whole page as one string. The route’s function returns it, dispatch() returns it, echo in index.php prints it on line 46. |
views/layout.php
<!doctype html>
<html lang="sk">
<head>
<meta charset="utf-8">
<title><?= e($title) ?></title>
<style>
body { font-family: system-ui, sans-serif; max-width: 60rem; margin: 2rem auto; padding: 0 1rem; }
nav a { margin-right: 1rem; }
table { border-collapse: collapse; margin-bottom: 2rem; }
th, td { border: 1px solid #999; padding: .3rem .6rem; text-align: left; }
th { background: #eee; }
dt { font-weight: bold; margin-top: .6rem; }
</style>
</head>
<body>
<nav>
<a href="<?= url('/') ?>">Úvod</a>
<a href="<?= url('/kontrola') ?>">Kontrola</a>
<a href="<?= url('/debug') ?>">Debug</a>
</nav>
<h1><?= e($title) ?></h1>
<?= $content ?>
</body>
</html>
| Line | Note |
|---|---|
| 5, 21 | $title came through view('home', ['title' => 'Úvod']) and extract() |
| 16–20 | the menu. Every link goes through url(), the prefix is written nowhere. In task 4.3 you add a link for each of your tables here. |
| 23 | the HTML of the view is inserted here ($content from view()). Without e(), because $content is finished HTML. |
views/debug.php and views/404.php
<table>
<tr><th>$_SERVER['REQUEST_METHOD']</th><td><?= e($_SERVER['REQUEST_METHOD']) ?></td></tr>
<tr><th>$_SERVER['SCRIPT_NAME']</th><td><?= e($_SERVER['SCRIPT_NAME']) ?></td></tr>
<tr><th>$_SERVER['REQUEST_URI']</th><td><?= e($_SERVER['REQUEST_URI']) ?></td></tr>
<tr><th>$prefix</th><td><?= e($prefix) ?></td></tr>
<tr><th>$path (relatívna adresa)</th><td><?= e($path) ?></td></tr>
</table>
<p>Zmeň koniec adresy v riadku s adresou na <code>/debug/</code>, <code>/debug?x=1</code> alebo <code>/Debug</code> a sleduj, čo sa v tabuľke zmení.</p>
| Line | Note |
|---|---|
| 2–4 | values Apache passed to PHP from the request |
| 5–6 | values index.php computed on lines 18–21; they came through view('debug', ['prefix' => $prefix, 'path' => $path]) |
| 8 | /debug/ gives the same $path (line 21 of index.php removes the slash); /Debug gives the 404 page (the route pattern distinguishes upper and lower case) |
<p>Pre túto adresu aplikácia nemá stránku (stavový kód 404).</p>
<p><a href="<?= url('/') ?>">Späť na úvod</a></p>
The 404 page is returned by Router::dispatch() (line 47 of Router.php) for an address without a route, and by the route function for /recipes/{id} for an id that is not in the table (Example 3).
views/kontrola.php
The check page from cv02 without the parts now done by index.php (configuration, autoload) and layout.php (<html>, <head>, <h1>, </html>). What remains is the code that reads tables and models, and the HTML from <h2> on. htmlspecialchars() is replaced by e(). You add your models to the $models array as in cv02.
```php views/kontrola.php, lines 1–15 query(‘SHOW TABLES’)->fetchAll(PDO::FETCH_COLUMN);
// 2. Your models – one line for each class: $models = [ // new (), // new (),]; ?>
| Line | Note |
|---|---|
| 3 | `use` works in a view too: a view is a PHP file loaded by `require` in `view()` |
| 11–14 | write `new \App\Model\YourModel(),` here for each of your classes (task 4.2) |
### Composer: the "files" block in composer.json
In `composer.json`, the `"autoload"` part has two keys. `"psr-4"` from cv02 tells Composer: the class `App\X` is in the file `src/X.php`; the file is loaded the moment the code uses the class `App\X` (for example `new Router()` loads `src/Router.php`). `"files"` tells Composer: load these files right at `require vendor/autoload.php`.
`src/helpers.php` is in `"files"`. It contains the functions `e()`, `url()` and `view()`, and thanks to this they are available from line 12 of `index.php` in every file of the application.
```json composer.json
{
"name": "tuke/it-projekt",
"description": "Semestrálny projekt – Informačné technológie",
"type": "project",
"require": {
"php": ">=8.1"
},
"autoload": {
"psr-4": {
"App\\": "src/"
},
"files": [
"src/helpers.php"
]
},
"config": {
"platform": {
"php": "8.1.2"
}
}
}
| Line | Note |
|---|---|
| 9–11 | from cv02: classes App\… are in src/ |
| 12–14 | new: the list of files vendor/autoload.php loads on every request. The path is relative to composer.json. |
When and where: after changing composer.json you run composer install in the terminal in Kubeflow in the folder ~/web/it/cv03. Composer creates vendor/ and in it the file vendor/composer/autoload_files.php with an entry for src/helpers.php. Then right-click cv03 → Upload Folder, so that vendor/ is on sigma.tuke.sk too.
How you verify: open …/cv03/. The home page with the menu appears. If Fatal error: Call to undefined function view() appears, vendor/ on sigma.tuke.sk is the one from cv02 without the entry for helpers.php: run composer install and upload vendor/ again with Upload Folder.
More: Composer: autoload files
How it works: recipe number 3 from the address to the page
What Ján Novák wants: to open recipe number 3. He clicks the number 3 in the recipe list, or types https://sigma.tuke.sk/student/jan.novak/it/cv03/recipes/3 and presses Enter. We go step by step.
Step 1. The browser sends a request.
GET /student/jan.novak/it/cv03/recipes/3 HTTP/1.1
Host: sigma.tuke.sk
Step 2. Apache on sigma.tuke.sk looks for a file and follows .htaccess. The file public_html/it/cv03/recipes/3 is not on disk. In .htaccess this applies:
RewriteCond %{REQUEST_FILENAME} !-f # the file "recipes/3" does not exist → condition holds
RewriteRule ^ index.php [L] # → Apache runs index.php
Before running it Apache fills the $_SERVER array:
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/student/jan.novak/it/cv03/recipes/3';
$_SERVER['SCRIPT_NAME'] = '/student/jan.novak/it/cv03/index.php';
Step 3. index.php runs. The lines executed for this request, with values in the comments:
$config = require __DIR__ . '/config.php'; // array with the database data; debug is true
require __DIR__ . '/vendor/autoload.php'; // from now on PHP finds the App\... classes and has e(), url(), view()
$prefix = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/'); // '/student/jan.novak/it/cv03'
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // '/student/jan.novak/it/cv03/recipes/3'
$path = substr($path, strlen($prefix)); // '/recipes/3'
$path = '/' . trim($path, '/'); // '/recipes/3'
define('BASE_URL', $prefix); // for the function url()
$router = new Router(); // empty route list
$router->get('/', ...); // routes are only stored, the functions do not run
$router->get('/recipes', ...);
$router->get('/recipes/{id}', function (int $id): string { // route for our detail (Example 3)
$model = new \App\Model\RecipeModel();
$row = $model->getById($id);
if ($row === null) {
http_response_code(404);
return view('404', ['title' => 'Nenájdené']);
}
return view('show', ['title' => $row['title'], 'row' => $row, 'back' => '/recipes']);
});
echo $router->dispatch($_SERVER['REQUEST_METHOD'], $path); // dispatch('GET', '/recipes/3') – step 4
Step 4. Router::dispatch('GET', '/recipes/3') looks for a route. In src/Router.php the list is walked. At the route /recipes/{id}, whose pattern after add() is the text #^/recipes/(\d+)$#:
if (preg_match('#^/recipes/(\d+)$#', '/recipes/3', $m)) { // match; (\d+) captured '3'
array_shift($m); // $m was ['/recipes/3', '3'], now ['3']
$params = array_map('intval', $m); // [3] – text '3' → number 3
return ($route['handler'])(...$params); // calls the route function with $id = 3
}
Step 5. The route function for /recipes/{id} runs with $id = 3. new RecipeModel() creates the model (its constructor takes the database connection through Database::getInstance()). getById(3) sends the query SELECT r.*, d.name AS difficulty_name FROM recipes r JOIN difficulties d ON d.id = r.difficulty_id WHERE r.id = 3 and returns one record as an array: ['id' => 3, 'title' => '…', 'servings' => 4, …, 'difficulty_name' => 'ľahký']. The record exists, so view('show', […]) is called.
Step 6. view() builds the HTML. In src/helpers.php:
function view(string $name, array $data = []): string
{
extract($data); // $title, $row, $back
ob_start(); // output is captured, it does not go to the browser
require __DIR__ . '/../views/' . $name . '.php'; // runs views/show.php → <dl>...</dl>
$content = ob_get_clean(); // $content = '<dl>...</dl><p><a ...>Späť na zoznam</a></p>'
ob_start();
require __DIR__ . '/../views/layout.php'; // the layout puts $content into the page frame
return ob_get_clean(); // '<!doctype html>...the whole page...</html>'
}
The HTML of the whole page returns from view() to the route function, from the route function to dispatch(), from dispatch() to index.php.
Step 7. echo in index.php prints the HTML. Apache adds the first line HTTP/1.1 200 OK (PHP did not call http_response_code(), hence 200) and the headers, and sends the response to the browser. The browser shows the menu, the heading with the recipe title and the record as a list of column–value pairs.
For …/cv03/recipes/999 everything is the same up to getById(999), which returns null: the route function calls http_response_code(404) (Apache puts 404 Not Found into the first line) and returns view('404', …). For …/cv03/nic no route matches and dispatch() itself returns the 404 page (lines 46–47 of Router.php).
Most common errors and what they mean
| What you see | Cause | Fix |
|---|---|---|
Apache “Not Found” page without the application menu for …/cv03/debug |
.htaccess on sigma.tuke.sk is missing or has no lines 13–15 |
save .htaccess from router.zip, Upload Folder |
| status code 500 on every address | typo in .htaccess |
compare with the file in part 3 line by line |
Call to undefined function view() |
vendor/ on sigma.tuke.sk has no entry for helpers.php |
composer install in Kubeflow, Upload Folder |
Class "App\Router" not found |
src/Router.php is missing on sigma.tuke.sk |
Upload Folder |
| your 404 page for an address that has a route | the route is written after the line echo $router->dispatch(…), or the address in get() has a typo |
move get() before dispatch(); compare the address in get() with $path on the /debug page |
a menu link leads to sigma.tuke.sk/recipes |
the view has href="/recipes" instead of url('/recipes') |
use url() |
/recipes/abc gives the 404 page |
correct behaviour: (\d+) matches digits only |
nothing |
/debug shows $path as /index.php/debug |
the address contains index.php: …/cv03/index.php/debug |
type the address without index.php |
Failed opening required '…/views/list.php' |
there is no view with this name in views/, or its name differs from the one in view('list', …) |
file name without .php = first parameter of view() |
UkážkyExamples
Vzorová aplikácia beží na https://sigma.tuke.sk/beata.stehlikova/it/ukazky/cv03/. Zdrojové súbory sú vo vzor-cv03.zip.
Ukážka 1: požiadavka a odpoveď v prehliadači
/recipes/3, nižšie hlavičky požiadavky a odpovede. Druhý riadok zoznamu: /nic so stavovým kódom 404.
style.css existuje ako súbor, Apache ho pošle priamo. /recipes/3 ako súbor neexistuje, Apache spustí index.php.
Ukážka 2: .htaccess
Celý súbor je v časti 3. Test po nahraní: …/cv03/debug ukáže tabuľku; …/cv03/src/Router.php ukáže 404; …/cv03/config.php ukáže 403.
Ukážka 3: index.php vzorovej aplikácie: route pre číselníky a hlavnú entitu
Riadky 39–43 z index.php v router.zip sú vo vzorovej aplikácii nahradené týmito route:
```php index.php vzorovej aplikácie, riadky 39–75 // Číselníky: jedna route na zoznam pre každý. $router->get(‘/difficulties’, function (): string { $model = new (); return view(‘list’, [‘title’ => $model->describe(), ‘rows’ => $model->getAll()]); });
$router->get(‘/categories’, function (): string { $model = new (); return view(‘list’, [‘title’ => $model->describe(), ‘rows’ => $model->getAll()]); });
$router->get(‘/ingredients’, function (): string { $model = new (); return view(‘list’, [‘title’ => $model->describe(), ‘rows’ => $model->getAll()]); });
$router->get(‘/units’, function (): string { $model = new (); return view(‘list’, [‘title’ => $model->describe(), ‘rows’ => $model->getAll()]); });
// Hlavná entita: zoznam s odkazmi na detail. $router->get(‘/recipes’, function (): string { $model = new (); return view(‘list’, [‘title’ => $model->describe(), ‘rows’ => $model->getAll(), ‘show’ => ‘/recipes’]); });
// Detail: {id} z adresy príde ako $id. Záznam, ktorý v tabuľke nie je → 404. $router->get(‘/recipes/{id}’, function (int $id): string { $model = new (); $row = $model->getById($id); if ($row === null) { http_response_code(404); return view(‘404’, [‘title’ => ‘Nenájdené’]); } return view(‘show’, [‘title’ => $row[‘title’], ‘row’ => $row, ‘back’ => ‘/recipes’]); });
| Riadok | Poznámka |
|---|---|
| 2–5 | route pre číselník: vytvorí model, zavolá `getAll()` a dáta pošle view `list` s nadpisom z `describe()`. Riadky 7–20 sú to isté pre ďalšie tri číselníky; mení sa len relatívna adresa a názov triedy. |
| 23–26 | zoznam hlavnej entity. `'show' => '/recipes'` povie view `list.php`, kam vedie odkaz z `id` (Ukážka 4). |
| 29–37 | detail. Parameter `int $id` dostane číslo z adresy (časť 5). `getById()` z tvojho modelu vráti `null` pre neexistujúce `id`: vtedy stavový kód 404 a view `404`. Inak view `show` s riadkom a adresou späť na zoznam. |
Menu v `layout.php` má vo vzorovej aplikácii o päť odkazov viac: `url('/difficulties')`, `url('/categories')`, `url('/ingredients')`, `url('/units')`, `url('/recipes')`.
### Ukážka 4: views list.php a show.php
```php views/list.php
<?php /* Tabuľka záznamov. Očakáva: $rows (pole riadkov z getAll()), voliteľne $show (relatívna adresa detailu, napr. '/recipes'). */ ?>
<?php if (!$rows): ?>
<p>Tabuľka je prázdna – spusti seed.sql.</p>
<?php else: ?>
<p>Počet záznamov: <?= count($rows) ?></p>
<table>
<tr>
<?php foreach (array_keys($rows[0]) as $col): ?>
<th><?= e($col) ?></th>
<?php endforeach; ?>
</tr>
<?php foreach ($rows as $row): ?>
<tr>
<?php foreach ($row as $col => $v): ?>
<td>
<?php if ($col === 'id' && isset($show)): ?>
<a href="<?= url($show . '/' . $row['id']) ?>"><?= e((string) $v) ?></a>
<?php else: ?>
<?= e((string) $v) ?>
<?php endif; ?>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
| Riadok | Poznámka |
|---|---|
| 1 | komentár na začiatku view: ktoré premenné view očakáva. Tie prídu cez view('list', [...]) a extract(). |
| 8–10 | hlavička tabuľky z názvov stĺpcov prvého riadku; rovnaký postup ako kontrolná stránka v cv02 |
| 16–17 | v stĺpci id je odkaz, ak route poslala $show: url('/recipes' . '/' . 3) dá …/cv03/recipes/3. Číselníky $show neposielajú, ich id je obyčajný text. |
| 9, 17, 19 | každá hodnota z databázy ide cez e() |
<?php /* Jeden záznam. Očakáva: $row (asociatívne pole z getById()), $back (relatívna adresa zoznamu). */ ?>
<dl>
<?php foreach ($row as $col => $v): ?>
<dt><?= e($col) ?></dt>
<dd><?= nl2br(e((string) $v)) ?></dd>
<?php endforeach; ?>
</dl>
<p><a href="<?= url($back) ?>">Späť na zoznam</a></p>
| Riadok | Poznámka |
|---|---|
| 2–7 | <dl> je zoznam dvojíc názov (<dt>) a hodnota (<dd>); jedna dvojica pre každý stĺpec záznamu |
| 5 | nl2br() prevedie konce riadkov v texte na <br>; volá sa až po e(), aby <br> ostalo značkou |
| 8 | odkaz späť cez url(); $back poslala route ('/recipes') |
…/cv03/recipes: tabuľka z getAll() aj so stĺpcom difficulty_name z JOIN; id je odkaz na detail.
…/cv03/recipes/3: jeden záznam v <dl>, nadpis stránky je názov receptu.
Ukážka 5: stránka /debug a stránka 404
…/cv03/debug?x=1: päť hodnôt z časti 4. REQUEST_URI má aj ?x=1, $path nie.
…/cv03/nic: stránka 404 z views/404.php v ráme layout.php. V karte Network je stavový kód 404.
Ukážka 6: prompt na view
Do AI vlož src/helpers.php, views/layout.php, views/list.php a tento text:
Napíš PHP view views/show.php pre moju aplikáciu. Pravidlá:
- View dostane premenné $row (asociatívne pole jedného záznamu z getById()) a $back (relatívna adresa zoznamu).
- Každú hodnotu vypisuj cez funkciu e(), každý odkaz cez funkciu url(). Obe sú v priloženom helpers.php.
- Žiadne <html>, <head>, <body>: to robí priložený layout.php.
- Stĺpce vypíš ako <dl> s <dt> názov stĺpca a <dd> hodnota.
- Na konci odkaz „Späť na zoznam“ na adresu $back.
- Bez CSS, bez JavaScriptu, bez ďalších funkcií.
V odpovedi skontroluj:
| Čo | Správne |
|---|---|
| výpis hodnôt | každý <?= … ?> s hodnotou z $row má e() |
| odkazy | každý href má url() |
| rám stránky | v súbore nie je <html>, <head>, <body> ani <h1> |
| premenné | len $row a $back; iné by view nedostal |
The sample application runs at https://sigma.tuke.sk/beata.stehlikova/it/ukazky/cv03/. The source files are in vzor-cv03.zip.
Example 1: request and response in the browser
/recipes/3, below the request and response headers. Second row of the list: /nic with status code 404.
style.css exists as a file, Apache sends it directly. /recipes/3 does not exist as a file, Apache runs index.php.
Example 2: .htaccess
The whole file is in part 3. Test after uploading: …/cv03/debug shows the table; …/cv03/src/Router.php shows 404; …/cv03/config.php shows 403.
Example 3: index.php of the sample application: routes for lookup tables and the main entity
Lines 39–43 of index.php from router.zip are replaced in the sample application by these routes:
```php index.php of the sample application, lines 39–75 // Lookup tables: one list route for each. $router->get(‘/difficulties’, function (): string { $model = new (); return view(‘list’, [‘title’ => $model->describe(), ‘rows’ => $model->getAll()]); });
$router->get(‘/categories’, function (): string { $model = new (); return view(‘list’, [‘title’ => $model->describe(), ‘rows’ => $model->getAll()]); });
$router->get(‘/ingredients’, function (): string { $model = new (); return view(‘list’, [‘title’ => $model->describe(), ‘rows’ => $model->getAll()]); });
$router->get(‘/units’, function (): string { $model = new (); return view(‘list’, [‘title’ => $model->describe(), ‘rows’ => $model->getAll()]); });
// Main entity: list with links to the detail. $router->get(‘/recipes’, function (): string { $model = new (); return view(‘list’, [‘title’ => $model->describe(), ‘rows’ => $model->getAll(), ‘show’ => ‘/recipes’]); });
// Detail: {id} from the address arrives as $id. A record that is not in the table → 404. $router->get(‘/recipes/{id}’, function (int $id): string { $model = new (); $row = $model->getById($id); if ($row === null) { http_response_code(404); return view(‘404’, [‘title’ => ‘Nenájdené’]); } return view(‘show’, [‘title’ => $row[‘title’], ‘row’ => $row, ‘back’ => ‘/recipes’]); });
| Line | Note |
|---|---|
| 2–5 | route for a lookup table: creates the model, calls `getAll()` and sends the data to the `list` view with the heading from `describe()`. Lines 7–20 are the same for the other three lookup tables; only the relative address and the class name change. |
| 23–26 | list of the main entity. `'show' => '/recipes'` tells the view `list.php` where the link from `id` leads (Example 4). |
| 29–37 | detail. The parameter `int $id` receives the number from the address (part 5). `getById()` returns `null` for a non-existent `id` (week 3): then status code 404 and the `404` view. Otherwise the `show` view with the row and the address back to the list. |
The menu in `layout.php` of the sample application has five more links: `url('/difficulties')`, `url('/categories')`, `url('/ingredients')`, `url('/units')`, `url('/recipes')`.
### Example 4: views list.php and show.php
```php views/list.php
<?php /* Table of records. Expects: $rows (array of rows from getAll()), optionally $show (relative address of the detail, e.g. '/recipes'). */ ?>
<?php if (!$rows): ?>
<p>Tabuľka je prázdna – spusti seed.sql.</p>
<?php else: ?>
<p>Počet záznamov: <?= count($rows) ?></p>
<table>
<tr>
<?php foreach (array_keys($rows[0]) as $col): ?>
<th><?= e($col) ?></th>
<?php endforeach; ?>
</tr>
<?php foreach ($rows as $row): ?>
<tr>
<?php foreach ($row as $col => $v): ?>
<td>
<?php if ($col === 'id' && isset($show)): ?>
<a href="<?= url($show . '/' . $row['id']) ?>"><?= e((string) $v) ?></a>
<?php else: ?>
<?= e((string) $v) ?>
<?php endif; ?>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
| Line | Note |
|---|---|
| 1 | a comment at the start of the view: which variables the view expects. They come through view('list', [...]) and extract(). |
| 8–10 | table header from the column names of the first row; the same approach as the check page in cv02 |
| 16–17 | in the id column there is a link if the route sent $show: url('/recipes' . '/' . 3) gives …/cv03/recipes/3. Lookup tables do not send $show, their id is plain text. |
| 9, 17, 19 | every value from the database goes through e() |
<?php /* One record. Expects: $row (associative array from getById()), $back (relative address of the list). */ ?>
<dl>
<?php foreach ($row as $col => $v): ?>
<dt><?= e($col) ?></dt>
<dd><?= nl2br(e((string) $v)) ?></dd>
<?php endforeach; ?>
</dl>
<p><a href="<?= url($back) ?>">Späť na zoznam</a></p>
| Line | Note |
|---|---|
| 2–7 | <dl> is a list of pairs name (<dt>) and value (<dd>); one pair for each column of the record |
| 5 | nl2br() converts line breaks in the text to <br>; it is called after e(), so that <br> stays a tag |
| 8 | the link back through url(); $back was sent by the route ('/recipes') |
…/cv03/recipes: table from getAll() including the column difficulty_name from the JOIN; id is a link to the detail.
…/cv03/recipes/3: one record in a <dl>, the page heading is the recipe title.
Example 5: the /debug page and the 404 page
…/cv03/debug?x=1: the five values from part 4. REQUEST_URI includes ?x=1, $path does not.
…/cv03/nic: the 404 page from views/404.php in the layout.php frame. The Network tab shows status code 404.
Example 6: prompt for a view
Give the AI src/helpers.php, views/layout.php, views/list.php and this text:
Write the PHP view views/show.php for my application. Rules:
- The view receives the variables $row (associative array of one record from getById()) and $back (relative address of the list).
- Print every value through the function e(), every link through the function url(). Both are in the attached helpers.php.
- No <html>, <head>, <body>: the attached layout.php does that.
- Print the columns as a <dl> with <dt> column name and <dd> value.
- At the end a link "Späť na zoznam" to the address $back.
- No CSS, no JavaScript, no further functions.
In the answer check:
| What | Correct |
|---|---|
| printing values | every <?= … ?> with a value from $row has e() |
| links | every href has url() |
| page frame | the file has no <html>, <head>, <body> or <h1> |
| variables | only $row and $back; the view would not receive others |
Úlohy na cvičenieLab tasks
Úlohy dostaneš aj ako zadanie cv03 v Classroom 50, sú v súbore README.md v tvojom repository. Repository má na začiatku len README.md; súbory doň pridáš v úlohe 4.1.
Link na zadanie cv03: prijať zadanie (platí pre skupiny B. Stehlíkovej; ostatné skupiny dostanú link od svojho cvičiaceho)
Úloha 4.1: Repository cv03 z cv02 a router.zip. Prijmi zadanie cv03 (link je vyššie) a repository naklonuj do ~/web/it/cv03 podľa návodu 04 Odovzdávanie, časti 2 a 3 (posledné slovo príkazu je cv03). Potom v termináli:
cd ~/web/it
cp cv02/config.php cv02/config.example.php cv02/.gitignore cv03/
cp -r cv02/sql cv02/src cv03/
cd cv03
curl -O https://beata.stehlikova.website.tuke.sk/it/router.zip
unzip -o router.zip && rm router.zip
composer install
unzip -o prepíše .htaccess, composer.json a index.php novou verziou a pridá src/Router.php, src/helpers.php a views/. Potom pravý klik na priečinok cv03 → Upload Folder. Kontrola: https://sigma.tuke.sk/student/meno.priezvisko/it/cv03/ ukáže úvodnú stránku s menu, …/cv03/debug ukáže tabuľku s piatimi hodnotami, …/cv03/nic ukáže stránku 404. Commit a push: cv03: kostra s routerom.
Úloha 4.2: Kontrolná stránka. Vo views/kontrola.php doplň do poľa $models jeden riadok new \App\Model\TvojModel(), pre každú svoju triedu (rovnaké riadky ako v index.php z cv02). Ulož. Kontrola: …/cv03/kontrola zobrazí tabuľky a modely ako v cv02, v ráme s menu.
Úloha 4.3: Zoznamy. Vytvor views/list.php podľa Ukážky 4. V index.php pridaj pred riadok echo $router->dispatch(…) jednu route pre každý svoj číselník a jednu pre hlavnú entitu; relatívna adresa je /nazov-tabulky, vzor je v Ukážke 3. Do menu vo views/layout.php pridaj odkaz cez url() pre každú z nich. Kontrola: každá adresa zobrazí tabuľku záznamov; pri hlavnej entite je aj stĺpec z číselníka (JOIN z cv02).
Úloha 4.4: Detail. Vytvor views/show.php (Ukážka 4 alebo prompt z Ukážky 6). Pridaj route /hlavna-entita/{id} podľa Ukážky 3 a v route zoznamu hlavnej entity pošli view 'show' => '/hlavna-entita'. Kontrola: klik na id v zozname otvorí detail; …/hlavna-entita/999 ukáže stránku 404 a v karte Network stavový kód 404.
Úloha 4.5: Vlastná route. Pridaj route /o-aplikacii s view views/about.php: názov tvojej témy, zoznam tvojich tabuliek a odkaz na GitHub repository. Pridaj odkaz do menu. Kontrola: adresa funguje, odkaz v menu vedie na ňu.
Úloha 4.6: Odovzdanie. Commit a push podľa návodu 04 Odovzdávanie, časť 5. Na GitHub skontroluj, že je tam .htaccess, composer.json s blokom "files", index.php, src/Router.php, src/helpers.php, views/ so všetkými viewmi a tvoje src/Model/. config.php a vendor/ tam nie sú.
Úloha 4.7: Kontrola na sigma.tuke.sk. Pravý klik na cv03, Upload Folder. Preklikaj menu: úvod, každý číselník, hlavná entita, jeden detail, kontrola, o aplikácii. Potom over tri adresy: …/cv03/nic ukáže stránku 404, …/cv03/src/Router.php ukáže 404, …/cv03/config.php ukáže 403. Do README.md v cv03 doplň tabuľku všetkých svojich route: relatívna adresa a čo zobrazí.
Hodnotenie: 1 bod. Aplikácia vo webovom priestore na sigma.tuke.sk odpovedá na všetky adresy z tabuľky route v README; neexistujúca adresa vráti stavový kód 404. Commit a push najneskôr do nasledujúceho cvičenia. Tento týždeň je zároveň prvý míľnik: obhajoba týždňov 2–4.
You also get the tasks as the assignment cv03 in Classroom 50, in the file README.md in your repository. The repository starts with only README.md; you add the files in task 4.1.
Link to the assignment cv03: accept assignment (for B. Stehlíková’s groups; other groups get the link from their instructor)
Task 4.1: Repository cv03 from cv02 and router.zip. Accept the assignment cv03 (link above) and clone the repository into ~/web/it/cv03 following the guide 04 Odovzdávanie, parts 2 and 3 (the last word of the command is cv03). Then in the terminal:
cd ~/web/it
cp cv02/config.php cv02/config.example.php cv02/.gitignore cv03/
cp -r cv02/sql cv02/src cv03/
cd cv03
curl -O https://beata.stehlikova.website.tuke.sk/it/router.zip
unzip -o router.zip && rm router.zip
composer install
unzip -o overwrites .htaccess, composer.json and index.php with the new version and adds src/Router.php, src/helpers.php and views/. Then right-click the folder cv03 → Upload Folder. Check: https://sigma.tuke.sk/student/meno.priezvisko/it/cv03/ shows the home page with the menu, …/cv03/debug shows the table with five values, …/cv03/nic shows the 404 page. Commit and push: cv03: kostra s routerom.
Task 4.2: Check page. In views/kontrola.php add one line new \App\Model\YourModel(), to the $models array for each of your classes (the same lines as in index.php from cv02). Save. Check: …/cv03/kontrola shows the tables and models as in cv02, in the frame with the menu.
Task 4.3: Lists. Create views/list.php following Example 4. In index.php, before the line echo $router->dispatch(…), add one route for each of your lookup tables and one for the main entity; the relative address is /table-name, the pattern is in Example 3. Add a link through url() for each of them to the menu in views/layout.php. Check: every address shows the table of records; the main entity also has the column from the lookup table (JOIN from cv02).
Task 4.4: Detail. Create views/show.php (Example 4 or the prompt from Example 6). Add the route /main-entity/{id} following Example 3 and in the list route of the main entity send the view 'show' => '/main-entity'. Check: clicking an id in the list opens the detail; …/main-entity/999 shows the 404 page and the Network tab shows status code 404.
Task 4.5: Own route. Add the route /o-aplikacii with the view views/about.php: the name of your topic, the list of your tables and a link to the GitHub repository. Add a link to the menu. Check: the address works, the menu link leads to it.
Task 4.6: Submission. Commit and push following the guide 04 Odovzdávanie, part 5. On GitHub check that .htaccess, composer.json with the "files" block, index.php, src/Router.php, src/helpers.php, views/ with all views and your src/Model/ are there. config.php and vendor/ are not.
Task 4.7: Check on sigma.tuke.sk. Right-click cv03, Upload Folder. Click through the menu: home, every lookup table, the main entity, one detail, check page, about. Then verify three addresses: …/cv03/nic shows the 404 page, …/cv03/src/Router.php shows 404, …/cv03/config.php shows 403. Add a table of all your routes to README.md in cv03: relative address and what it shows.
Grading: 1 point. The application in your web space on sigma.tuke.sk answers all addresses from the route table in the README; a non-existent address returns status code 404. Commit and push by the next lab at the latest. This week is also the first milestone: defence of weeks 2–4.
Obhajoba a live codingDefence and live coding
Pri obhajobe budú použité iba zverejnené otázky a úlohy. Prvý míľnik (4. týždeň) pokrýva týždne 2–4: dostaneš jednu položku z „Vysvetli“, jednu z „Uprav“ a jednu zo „Zdôvodni“ z tohto týždňa alebo z 2. a 3. týždňa, spolu cca 5 minút.
Pred obhajobou si aktuálny stav projektu skopíruješ do samostatného priečinka, aby odovzdané zadanie ostalo nedotknuté. V termináli v Kubeflow:
cd ~/web/it
mkdir obhajoba1
cp -r cv03/. obhajoba1/
rm -rf obhajoba1/.git
Potom pravý klik na obhajoba1 → Upload Folder. Live coding sa robí v obhajoba1; uloženie v editore ide na sigma.tuke.sk samo; adresa je …/it/obhajoba1/. Repository a GitHub sa nemenia. Úlohy z „Uprav“ sú zároveň rozširujúce úlohy pre rýchlych: kto si ich vyskúša vopred, má obhajobu ľahšiu.
Vysvetli (code walkthrough)
Nad svojím projektom vieš povedať:
- Čo je požiadavka a čo odpoveď; ukáž obe v karte Network pre jednu adresu svojej aplikácie.
- Čo je HTTP metóda a čo je cesta; kde ich má PHP.
- Čo je stavový kód; ukáž adresu svojej aplikácie so stavovým kódom 200 a adresu so stavovým kódom 404.
- Čo je
.htaccessa kedy ho Apache čítá. - Čo robí každý z riadkov
RewriteEngine On,RewriteCond %{REQUEST_FILENAME} !-f,RewriteRule ^ index.php [L]. - Prečo požiadavka na
…/cv03/src/Router.phpdostane 404, hoci súbor existuje. - Čo je prefix a čo relatívna adresa; ukáž obe na stránke
/debugsvojej aplikácie. - Čo robí každý zo štyroch riadkov, ktoré počítajú
$pathvindex.php. - Prečo je ten istý
index.phpsprávny u teba aj u učiteľa. - Čo je front controller a ktorý súbor ním je.
- Čo je Router a čo je route; koľko route má tvoja aplikácia.
- Čo robí
get()a čodispatch(); kedy sa spúšťa funkcia zapísaná vget(). - Prečo je
echo $router->dispatch(…)posledný riadokindex.php. - Čo je
{id}v adrese route a na čo ho Router nahradí; čo znamená(\d+). - Čo je v
$mpopreg_match()a prečo sa$m[0]zahadzuje. - Čo robí
view(): čo robíextract(), čoob_start()aob_get_clean(). - Prečo view
layout.phpdostane$titlea odkiaľ. - Čo robí
url(); kam vedie odkazhref="/recipes"bezurl()a kam surl(). - Čo robí
e()a prečo je pri každej hodnote z databázy. - Čo hovorí blok
"files"vcomposer.jsona kedy sasrc/helpers.phpnačíta.
Uprav (live coding)
Zmeny v kóde vidno v prehliadači po uložení. Nič z toho trvalo nemení dáta.
- Pridaj route
/pocets view, ktorý vypíše počet záznamov hlavnej entity (getCount()). - Pridaj do stránky
/debugriadok s$_SERVER['HTTP_HOST']. - Zmeň text stránky 404 a pridaj do nej odkaz na zoznam hlavnej entity cez
url(). - Pridaj do menu v
layout.phpodkaz na detail záznamu sid1. - Zmeň route detailu tak, aby pre
id, ktoré v tabuľke nie je, zobrazila zoznam namiesto stránky 404. - Uprav
list.phptak, aby vypísal len prvé 3 záznamy (array_slice). - Pridaj do
show.phpnadpis „Záznam č. N“, kde N jeidz$row. - Pridaj route
/ciselnik/{id}pre jeden svoj číselník, ktorá zobrazí jeden záznam cezshow.php. - Pridaj do
helpers.phpfunkciuactive(string $path): string, ktorá vráti' class="active"', ak je$pathaktuálna relatívna adresa; použi ju v menu. - Vysvetli bez spúšťania, čo vráti
dispatch()pre adresy/recipes/3/,/Recipes/3,/recipes/03,/recipes/3?x=1; potom to over v prehliadači.
Zdôvodni (design decisions)
- Prečo
recipes/3a nierecipes.php?id=3. - Prečo má aplikácia jeden
index.phppre všetky adresy a nie jeden súbor pre každú stránku. - Prečo
view()HTML vracia ako reťazec a nevypisuje ho rovno cezecho. - Prečo je HTML rám v
layout.phpa nie v každom view. - Prečo odkazy idú cez
url()a nie cez napísaný prefix. - Prečo stránku 404 robí Router a nie
ErrorDocumentv.htaccess.
Definition of Done
Týždeň je hotový, keď:
…/cv03/debugvo webovom priestore na sigma.tuke.sk zobrazí tabuľku s piatimi hodnotami,- každý číselník a hlavná entita majú route na zoznam, hlavná entita aj route na detail; všetky sú v menu,
…/cv03/hlavna-entita/999a…/cv03/niczobrazia stránku 404 a v karte Network je stavový kód 404,…/cv03/src/Router.phpvráti 404 a…/cv03/config.phpvráti 403,README.mdmá tabuľku route,- commit a push sú na GitHub,
vendor/aniconfig.phpv repository nie sú.
Only the published questions and tasks will be used at the defence. The first milestone (week 4) covers weeks 2–4: you get one item from “Explain”, one from “Change” and one from “Justify”, from this week or from week 2 and week 3, about 5 minutes in total.
Before the defence you copy the current state of the project into a separate folder, so that the submitted assignment stays untouched. In the terminal in Kubeflow:
cd ~/web/it
mkdir obhajoba1
cp -r cv03/. obhajoba1/
rm -rf obhajoba1/.git
Then right-click obhajoba1 → Upload Folder. Live coding is done in obhajoba1; saving in the editor goes to sigma.tuke.sk by itself; the address is …/it/obhajoba1/. The repository and GitHub do not change. The “Change” tasks are also extension tasks for the fast: whoever tries them in advance has an easier defence.
Explain (code walkthrough)
Over your own project you can say:
- What a request is and what a response is; show both in the Network tab for one address of your application.
- What the HTTP method is and what the path is; where PHP has them.
- What a status code is; show an address of your application with status code 200 and one with status code 404.
- What
.htaccessis and when Apache reads it. - What each of the lines
RewriteEngine On,RewriteCond %{REQUEST_FILENAME} !-f,RewriteRule ^ index.php [L]does. - Why a request for
…/cv03/src/Router.phpgets 404 although the file exists. - What the prefix is and what the relative address is; show both on the
/debugpage of your application. - What each of the four lines that compute
$pathinindex.phpdoes. - Why the same
index.phpis correct for you and for the teacher. - What the front controller is and which file it is.
- What the Router is and what a route is; how many routes your application has.
- What
get()does and whatdispatch()does; when the function written inget()runs. - Why
echo $router->dispatch(…)is the last line ofindex.php. - What
{id}in a route address is and what the Router replaces it with; what(\d+)means. - What is in
$mafterpreg_match()and why$m[0]is dropped. - What
view()does: whatextract()does, whatob_start()andob_get_clean()do. - Why the view
layout.phpreceives$titleand from where. - What
url()does; where the linkhref="/recipes"leads withouturl()and where withurl(). - What
e()does and why it is at every value from the database. - What the
"files"block incomposer.jsonsays and whensrc/helpers.phpis loaded.
Change (live coding)
Changes in the code are visible in the browser after saving. None of this changes data permanently.
- Add the route
/pocetwith a view that prints the number of records of the main entity (getCount()). - Add a row with
$_SERVER['HTTP_HOST']to the/debugpage. - Change the text of the 404 page and add a link to the list of the main entity through
url(). - Add a link to the detail of the record with
id1 to the menu inlayout.php. - Change the detail route so that for an
idthat is not in the table it shows the list instead of the 404 page. - Change
list.phpso that it prints only the first 3 records (array_slice). - Add the heading “Záznam č. N” to
show.php, where N is theidfrom$row. - Add the route
/lookup/{id}for one of your lookup tables, showing one record throughshow.php. - Add the function
active(string $path): stringtohelpers.php, which returns' class="active"'if$pathis the current relative address; use it in the menu. - Explain without running what
dispatch()returns for the addresses/recipes/3/,/Recipes/3,/recipes/03,/recipes/3?x=1; then verify it in the browser.
Justify (design decisions)
- Why
recipes/3and notrecipes.php?id=3. - Why the application has one
index.phpfor all addresses and not one file per page. - Why
view()returns the HTML as a string and does not print it directly withecho. - Why the HTML frame is in
layout.phpand not in every view. - Why links go through
url()and not through a written prefix. - Why the Router makes the 404 page and not
ErrorDocumentin.htaccess.
Definition of Done
The week is done when:
…/cv03/debugin your web space on sigma.tuke.sk shows the table with five values,- every lookup table and the main entity have a list route, the main entity also a detail route; all are in the menu,
…/cv03/main-entity/999and…/cv03/nicshow the 404 page and the Network tab shows status code 404,…/cv03/src/Router.phpreturns 404 and…/cv03/config.phpreturns 403,README.mdhas the route table,- commit and push are on GitHub, neither
vendor/norconfig.phpis in the repository.