Informačné technológieInformation Technologies / Týždeň 5Week 5

MVC: controller, view, request, responseMVC: controller, view, request, response

PojmyTerms Ako to funguje: kto koho voláHow it works: who calls whom Fyzická podoba: priečinky, súbory, autoloaderPhysical form: folders, files, autoloader Úlohy na cvičenieLab tasks Obhajoba a live codingDefence and live coding

Dnes dostane kód aplikácie štruktúru, akú má väčšina PHP aplikácií: rozdelenie na modely (práca s databázou; máš ich v src/Model/), views (HTML stránok; máš ich vo views/) a controllery (kód, ktorý pre jednu adresu zavolá model a vyberie view; pribudnú do src/Controller/). Požiadavku z prehliadača bude zastupovať objekt Request, odpoveď objekt Response. Aplikácia bude v prehliadači vyzerať rovnako ako doteraz a pribudne vyhľadávanie v zozname hlavnej entity. Vzorová aplikácia beží na https://sigma.tuke.sk/beata.stehlikova/it/ukazky/cv04/. Pojmy sú v tabuľke pojmov.

Celá stránka sleduje jedného študenta, Jána Nováka, a jeho číselník categories so štyrmi záznamami: polievka, hlavné jedlo, dezert, raňajky. Vo svojom projekte má src/Model/CategoryModel.php s metódami getAll() a describe() (jeho describe() vracia text Kategórie) a views/list.php, ktorý z poľa záznamov vyrobí HTML tabuľku.

Slovo view sa na tejto stránke používa pre priečinok views/, pre súbor v ňom (views/list.php) a pre funkciu view() v src/helpers.php, ktorá z takého súboru vyrobí HTML. Slovo metóda sa používa pre HTTP metódu (GET) aj pre metódu triedy (getAll()); v texte je vždy napísané celé, o ktorú ide. Všetko v src/ je náš kód: napísali sme ho pre tento predmet a dá sa otvoriť a čítať. Pri každom súbore je napísané, čo z PHP samotného používa.

Today the application code gets the structure most PHP applications have: a split into models (database work; you have them in src/Model/), views (the HTML of the pages; you have them in views/) and controllers (code that, for one address, calls a model and picks a view; they go into src/Controller/). The request from the browser will be represented by a Request object, the response by a Response object. In the browser the application will look the same as before, plus a search box in the main entity list. The sample application runs at https://sigma.tuke.sk/beata.stehlikova/it/ukazky/cv04/. Terms are in the terms table.

The whole page follows one student, Ján Novák, and his lookup table categories with four records: polievka, hlavné jedlo, dezert, raňajky. In his project he has src/Model/CategoryModel.php with the methods getAll() and describe() (his describe() returns the text Kategórie) and views/list.php, which turns an array of records into an HTML table.

On this page the word view is used for the folder views/, for a file in it (views/list.php) and for the function view() in src/helpers.php, which turns such a file into HTML. The word method is used for the HTTP method (GET) and for a class method (getAll()); the text always says which one. Everything in src/ is our code: we wrote it for this course and you can open and read it. For every file the text says what it uses from PHP itself.

PojmyTerms

Apache

Čo to je: program na serveri sigma.tuke.sk, ktorý prijíma požiadavky z prehliadačov a posiela späť odpovede. Beží stále; ty ho nespúšťaš ani nenastavuješ, patrí správcovi servera. V Kubeflow žiadny Apache nie je, preto sa stránka testuje vždy na adrese sigma.tuke.sk/student/….

Čo robí: keď príde požiadavka na adresu https://sigma.tuke.sk/student/jan.novak/it/cv04/categories, Apache vezme cestu /student/jan.novak/it/cv04/categories, premení ju na miesto na disku (/student/jan.novak/ je priečinok public_html Jána Nováka) a hľadá tam súbor it/cv04/categories. Keď nájde obyčajný súbor (obrázok, CSS), pošle ho prehliadaču tak, ako je. Keď nájde súbor .php, spustí ho a prehliadaču pošle to, čo PHP vypísalo. Keď nič nenájde, riadi sa súborom .htaccess (nižšie); keď ani ten nepovie inak, pošle odpoveď „404 Not Found“.

S čím sa prepája: s prehliadačom (dostane požiadavku, vráti odpoveď), s .htaccess (pravidlá pre priečinok) a s PHP (spustí index.php a naplní mu pole $_SERVER).

Požiadavka a odpoveď

Čo to je: rozhovor prehliadača so serverom má vždy dva kroky. Prehliadač pošle požiadavku (request), Apache vráti odpoveď (response). Jedna požiadavka, jedna odpoveď. Pravidlá tohto rozhovoru sa volajú HTTP.

Čo je v požiadavke: keď Ján Novák napíše adresu a stlačí Enter, prehliadač z nej zostaví a pošle tento text:

GET /student/jan.novak/it/cv04/categories HTTP/1.1
Host: sigma.tuke.sk

GET je HTTP metóda: druh požiadavky, „daj mi stránku“. Prehliadač ju použije pri adrese napísanej do riadka, pri kliknutí na odkaz a pri formulári s method="get". Za ňou je cesta: časť adresy za názvom servera. Host je názov servera.

Čo je v odpovedi:

HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8

<!doctype html>
<html lang="sk"> …

Prvý riadok má stavový kód: číslo, ako požiadavka dopadla; 200 znamená „stránka je tu“, 404 znamená „pre túto cestu nemám stránku“. Riadok Content-Type: … je hlavička: informácia pre prehliadač, tu „telo je HTML v kódovaní UTF-8“. Po prázdnom riadku je telo: HTML, ktoré prehliadač zobrazí.

S čím sa prepája: v našej aplikácii požiadavku zastupuje objekt Request a odpoveď objekt Response (pojmy nižšie); stavový kód a hlavičky píše PHP cez funkcie http_response_code() a header(), telo cez echo. Celú požiadavku aj odpoveď vidíš v prehliadači: F12 → karta Network → F5 → klik na prvý riadok → karta Headers.

.htaccess

Čo to je: textový súbor s názvom presne .htaccess (bodka na začiatku, bez prípony) s nastaveniami pre Apache. Platí pre priečinok, v ktorom leží, a pre všetky jeho podpriečinky. Každý riadok je jeden príkaz pre Apache; takýto príkaz sa volá direktíva.

Kde to je: v koreni aplikácie, vedľa index.php: v Kubeflow ~/web/it/cv04/.htaccess, na sigma.tuke.sk public_html/it/cv04/.htaccess, na GitHub v repository. Linux ho považuje za skrytý súbor: v termináli ho ukáže ls -a, Explorer vo VS Code ho ukáže sivšie.

Kedy sa použije: Apache na sigma.tuke.sk ho prečíta pri každej požiadavke do tohto priečinka. Uložíš súbor v Kubeflow, SFTP ho prenesie, a ďalšia požiadavka už ide podľa nového obsahu; nič sa nereštartuje. Preklep v názve direktívy znamená stavový kód 500 pre každú adresu v priečinku, kým preklep neopravíš.

Čo robí: celý .htaccess tvojej aplikácie; máš ho z cv03 bez zmeny:

.htaccess
# 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]

Čo urobí ktorá direktíva:

  • Riadok 2, RedirectMatch 404 …: pre cestu, v ktorej je /src/, /vendor/, /sql/ alebo /.git/, vráti stavový kód 404, aj keď súbor existuje. …/cv04/src/Router.php → 404; kód ostáva na serveri, ale z prehliadača sa nedá prečítať.
  • Riadky 5–7, <Files "config.php"> Require all denied: súbor config.php sa z prehliadača nedá otvoriť (stavový kód 403); PHP ho načítava normálne. …/cv04/config.php → 403; heslo k databáze ostáva skryté.
  • Riadok 10, IndexIgnore *: priečinok bez index.php nevypíše zoznam svojich súborov. …/cv04/views/ → prázdna stránka namiesto zoznamu súborov.
  • Riadok 13, RewriteEngine On: zapne prepisovanie ciest; bez tohto riadku Apache riadky 14 a 15 ignoruje.
  • Riadok 14, RewriteCond %{REQUEST_FILENAME} !-f: podmienka pre nasledujúce pravidlo. %{REQUEST_FILENAME} je súbor na disku, ktorý zodpovedá ceste z požiadavky: pre …/cv04/categories je to public_html/it/cv04/categories, pre …/cv04/css/style.css je to public_html/it/cv04/css/style.css. !-f znamená „nie je to existujúci súbor“. public_html/it/cv04/categories neexistuje → podmienka platí → riadok 15 spustí index.php. public_html/it/cv04/css/style.css existuje → podmienka neplatí → Apache pošle súbor tak, ako je.
  • Riadok 15, RewriteRule ^ index.php [L]: pravidlo: ak podmienka platí, požiadavku obslúž súborom index.php. ^ sedí na každú cestu, [L] znamená „posledné pravidlo“. Pôvodná cesta ostáva zachovaná pre PHP. …/cv04/categories → Apache spustí index.php; …/cv04/recipes/3 → tiež index.php.

Riadky 13–15 sú dôvod, prečo aplikácia má adresy …/categories a …/recipes/3 bez .php a bez ?id=: každá taká adresa skončí v jedinom súbore index.php a ten sa podľa cesty rozhodne, čo zobrazí.

S čím sa prepája: s Apache (ten ho číta) a s index.php (tam riadky 13–15 posielajú každú adresu, ktorá nie je súbor).

$_SERVER a $_GET

Čo to je: polia, ktoré PHP dostane pri každej požiadavke už naplnené. Plní ich Apache z textu požiadavky, skôr než spustí index.php. Sú dostupné v každom súbore aplikácie bez require a bez parametra.

Čo je v nich pre požiadavku GET /student/jan.novak/it/cv04/categories:

$_SERVER['REQUEST_METHOD'] = 'GET';                                  // prvé slovo požiadavky
$_SERVER['REQUEST_URI']    = '/student/jan.novak/it/cv04/categories'; // cesta, aj s prípadnou časťou za '?'
$_SERVER['SCRIPT_NAME']    = '/student/jan.novak/it/cv04/index.php';  // súbor, ktorý Apache spustil
$_GET = [];                                                          // dvojice názov=hodnota za '?'; tu nič

Pre adresu …/cv04/recipes?q=tofu by bolo $_GET = ['q' => 'tofu'].

S čím sa prepája: v našej aplikácii ich číta jediné miesto, metóda Request::fromGlobals() (pojem Request nižšie). Nikde inde sa $_SERVER ani $_GET nepíše.

index.php

Čo to je: jediný PHP súbor, ktorý Apache spúšťa. Všetky ostatné súbory (src/, views/) sa spustia len tým, že ich index.php priamo alebo nepriamo načíta. Takýto súbor sa volá front controller: jeden vchod do aplikácie.

Kde to je: koreň aplikácie, ~/web/it/cv04/index.php.

Čo robí: pri každej požiadavke, v tomto poradí: načíta config.php a zapne výpis chýb; načíta vendor/autoload.php, aby PHP našlo naše triedy; z $_SERVER a $_GET vyrobí objekt Request; naplní zoznam adries v Routeri; požiadavku spracuje a odpoveď pošle. Celý súbor je v časti „Ako to funguje“, riadok po riadku.

S čím sa prepája: spúšťa ho Apache (riadok 15 .htaccess); on vytvára Request a Router; Router volá controller; index.php nakoniec pošle Response.

MVC

Čo to je: spôsob, ako je rozdelený kód aplikácie do skupín podľa toho, čo robí. Názov je z prvých písmen skupín: Model, View, Controller. Navrhol ho Trygve Reenskaug v roku 1979 pre programy s grafickým rozhraním; dnes je to bežná stavba webových aplikácií v PHP aj v iných jazykoch.

Načo to je: každý druh kódu má svoje miesto. Kto to pozná, vie aj v cudzom projekte, kde čo hľadať: dotaz do databázy v modeli, HTML vo view, rozhodnutie „čo pre túto adresu urobiť“ v controlleri. Keď nefunguje stránka kategórií, otvoríš CategoryController.php; keď je zle zoradená tabuľka, otvoríš CategoryModel.php; keď je zle HTML, otvoríš views/list.php.

Skupina Čo robí Priečinok V tvojom projekte
Model číta a zapisuje dáta jednej tabuľky v databáze src/Model/ máš od cv02
View vyrobí HTML jednej stránky z hodnôt, ktoré dostane views/ máš od cv03
Controller pre jednu adresu vytvorí model, zavolá jeho metódu a dáta pošle view src/Controller/ pribudne dnes

S čím sa prepája: Controller volá Model a View; Model nevie o View ani o Controlleri; View dostane hotové hodnoty a nič nepočíta. Kto koho volá, je v časti „Ako to funguje“.

Model

Čo to je: trieda, ktorá pracuje s jednou tabuľkou v databáze. Pre každú tabuľku okrem prepojok je jeden súbor s jednou triedou. Je to náš kód.

Kde to je: src/Model/, napríklad src/Model/CategoryModel.php Jána Nováka pre tabuľku categories:

src/Model/CategoryModel.php
<?php
declare(strict_types=1);

namespace App\Model;

class CategoryModel extends BaseModel        // zdedí getAll(), getById(), getCount() a konštruktor
{
    protected string $table = 'categories';  // tabuľka, s ktorou tento model pracuje

    public function describe(): string
    {
        return 'Kategórie';                  // nadpis pre stránku
    }
}

Čo robí: trieda dedí od BaseModel (src/Model/BaseModel.php), v ktorom sú hotové metódy pre každú tabuľku. Čo vrátia pre categories:

$model = new CategoryModel();
$model->getAll();     // [['id' => 1, 'name' => 'polievka'], ['id' => 2, 'name' => 'hlavné jedlo'],
                      //  ['id' => 3, 'name' => 'dezert'],   ['id' => 4, 'name' => 'raňajky']]
$model->getById(3);   // ['id' => 3, 'name' => 'dezert'];  pre id, ktoré v tabuľke nie je: null
$model->getCount();   // 4
$model->describe();   // 'Kategórie'

Pripojenie k databáze si model berie v konštruktore BaseModel cez Database::getInstance() (src/Database.php). Database je singleton: pripojenie vytvorí raz, pri prvom zavolaní, a potom vracia to isté. Pripája sa z PHP na sigma.tuke.sk k databáze na tom istom serveri. Z PHP používa triedu PDO.

S čím sa prepája: s databázou (cez PDO) a s controllerom, ktorý ho vytvorí (new CategoryModel()) a zavolá jeho metódu. Model nevie, kto ho volá, ani čo sa s dátami stane.

View

Čo to je: PHP súbor v priečinku views/, ktorý obsahuje HTML jednej stránky a na vyznačených miestach vypisuje hodnoty, ktoré dostal. Nič nepočíta a do databázy nechodí. Je to náš kód.

Kde to je: views/. Pre číselník kategórií sa použijú views/list.php (tabuľka záznamov) a views/layout.php (spoločný rám každej stránky: <html>, <head>, menu, nadpis).

Čo robí: views/list.php dostane premenné $title a $rows a vyrobí z nich HTML tabuľku; pre štyri kategórie Jána Nováka vyjde <table> so štyrmi riadkami a stĺpcami id a name. views/layout.php dostane $title a $content (hotové HTML z list.php) a vloží ich do rámu stránky.

Súbor vo views/ nikto nespúšťa priamo. Spúšťa ho funkcia view() v src/helpers.php, náš kód:

src/helpers.php
/** Vyrobí HTML stránky: načíta views/<name>.php, výsledok vloží do views/layout.php a vráti ako text. */
function view(string $name, array $data = []): string
{
    // ['title' => 'Kategórie', 'rows' => [...]]  →  $title = 'Kategórie'; $rows = [...]
    extract($data);

    // views/list.php vypisuje HTML (<?= ... ?>), ako keby išlo rovno do prehliadača.
    // ob_start() výpis zachytí: od tejto chvíle sa nič neposiela, všetko sa ukladá do pamäte.
    ob_start();
    require __DIR__ . '/../views/' . $name . '.php';     // spustí views/list.php
    $content = ob_get_clean();                            // vráti zachytený text, zachytávanie vypne
    // $content = '<p>Počet záznamov: 4</p><table>...</table>'

    // To isté s views/layout.php, ktorý má na svojom mieste <?= $content ?>.
    ob_start();
    require __DIR__ . '/../views/layout.php';
    return ob_get_clean();                                // '<!doctype html>...celá stránka...</html>'
}

view('list', ['title' => 'Kategórie', 'rows' => $rows]) urobí: z poľa vyrobí premenné $title a $rows (extract(), z PHP), spustí views/list.php a jeho výpis zachytí do textu (ob_start() a ob_get_clean(), z PHP), to isté s views/layout.php, a vráti HTML celej stránky ako jeden text. Nič nevypíše.

S čím sa prepája: funkciu view() volá controller cez render() (pojem Controller nižšie); hodnoty pre view pripraví controller z dát modelu; HTML, ktoré view() vráti, ide do objektu Response.

Request

Čo to je: objekt, ktorý zastupuje jednu požiadavku z prehliadača. Má v sebe HTTP metódu, prefix, relatívnu adresu a hodnoty za ?, teda všetko, čo aplikácia o požiadavke potrebuje vedieť. Trieda Request je náš kód.

Kde to je: src/Http/Request.php. Priečinok Http je nový; volá sa tak, lebo Request a Response sú strany HTTP rozhovoru.

Čo robí: pri každej požiadavke vznikne jeden objekt, v index.php riadkom $request = Request::fromGlobals();. fromGlobals() prečíta $_SERVER a $_GET a hodnoty uloží do objektu. Pre adresu Jána Nováka …/cv04/categories:

$request->method();     // 'GET'                         HTTP metóda
$request->prefix();     // '/student/jan.novak/it/cv04'  prefix: časť cesty, ktorá je vo všetkých
                        //                               adresách Jána Nováka rovnaká; u každého iná
$request->path();       // '/categories'                 relatívna adresa: cesta bez prefixu; s ňou pracuje Router
$request->query('q');   // ''                            hodnota parametra q za '?'; tu nič za '?' nie je

Celý súbor:

src/Http/Request.php
<?php
declare(strict_types=1);

namespace App\Http;

/**
 * Request: požiadavka z prehliadača ako objekt. Hodnoty, ktoré Apache dal do $_SERVER a $_GET,
 * sú tu ako vlastnosti s metódami na čítanie. Vzniká raz za požiadavku, v index.php, cez fromGlobals().
 */
final class Request
{
    // Vlastnosti sú private: zapíšu sa raz v konštruktore, potom sa len čítajú metódami.
    private string $method;   // 'GET'
    private string $prefix;   // '/student/jan.novak/it/cv04'
    private string $path;     // '/categories'
    private array  $query;    // ['q' => 'tofu']

    public function __construct(string $method, string $prefix, string $path, array $query)
    {
        $this->method = $method;
        $this->prefix = $prefix;
        $this->path   = $path;
        $this->query  = $query;
    }

    /**
     * Zostaví Request z polí $_SERVER a $_GET, ktoré naplnil Apache.
     * static: metóda patrí triede, volá sa bez objektu zápisom Request::fromGlobals().
     * "::" znamená „z triedy vezmi“; pri objekte sa píše "->". Rovnako Database::getInstance().
     */
    public static function fromGlobals(): self
    {
        $prefix = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');       // '/student/jan.novak/it/cv04'
        $path   = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);   // '/student/jan.novak/it/cv04/categories'
        $path   = substr($path, strlen($prefix));                     // '/categories'
        $path   = '/' . trim($path, '/');                             // '/categories'  (pre '.../cv04/' vyjde '/')

        return new self($_SERVER['REQUEST_METHOD'], $prefix, $path, $_GET);   // objekt Request
    }

    public function method(): string
    {
        return $this->method;
    }

    public function prefix(): string
    {
        return $this->prefix;
    }

    public function path(): string
    {
        return $this->path;
    }

    /**
     * Parameter z adresy za '?'. Pre ?q=tofu je $this->query = ['q' => 'tofu'] a query('q') vráti 'tofu'.
     * Pre adresu bez '?' je $this->query = [] a query('q') vráti $default, teda ''.
     * "??" znamená: ak ľavá strana neexistuje, použi pravú.
     */
    public function query(string $key, string $default = ''): string
    {
        return (string) ($this->query[$key] ?? $default);
    }
}

Z PHP používa $_SERVER, $_GET a funkcie dirname(), rtrim(), trim(), substr(), strlen(), parse_url().

S čím sa prepája: vytvorí ho index.php, podáva sa Routeru (ten z neho číta method() a path()) a controlleru (ten z neho číta query()). $_SERVER a $_GET číta v celej aplikácii len metóda fromGlobals().

Response

Čo to je: objekt, ktorý zastupuje jednu odpoveď pre prehliadač: stavový kód, hlavičky a telo. Trieda Response je náš kód.

Kde to je: src/Http/Response.php.

Čo robí: controller ju vytvorí a vráti; index.php ju pošle metódou send(). Pre stránku kategórií Jána Nováka je v objekte stavový kód 200, hlavička Content-Type: text/html; charset=UTF-8 a telo: HTML celej stránky z funkcie view().

src/Http/Response.php
<?php
declare(strict_types=1);

namespace App\Http;

/**
 * Response: odpoveď pre prehliadač ako objekt: stavový kód, hlavičky, telo.
 * Controller ju vráti, index.php ju pošle metódou send().
 */
final class Response
{
    private string $body;      // HTML
    private int    $status;    // 200, 404, ...
    private array  $headers;   // ['Content-Type' => 'text/html; charset=UTF-8']

    // new Response($html) stačí pre bežnú stránku: $status je predvolene 200, hlavičky prázdne.
    public function __construct(string $body, int $status = 200, array $headers = [])
    {
        $this->body    = $body;
        $this->status  = $status;
        // "+" spojí dve polia; pri rovnakom kľúči ostane hodnota z ľavého.
        // [] + ['Content-Type' => 'text/html...']                 → ['Content-Type' => 'text/html...']
        // ['Content-Type' => 'text/plain'] + ['Content-Type' => 'text/html...'] → ['Content-Type' => 'text/plain']
        $this->headers = $headers + ['Content-Type' => 'text/html; charset=UTF-8'];
    }

    public function status(): int
    {
        return $this->status;
    }

    public function body(): string
    {
        return $this->body;
    }

    /**
     * Pošle odpoveď prehliadaču. Naša metóda; z PHP používa http_response_code(), header() a echo.
     * Volá sa raz, v poslednom riadku index.php.
     */
    public function send(): void
    {
        http_response_code($this->status);            // Apache dá číslo do prvého riadku odpovede
        foreach ($this->headers as $name => $value) {
            header($name . ': ' . $value);            // riadok 'Content-Type: text/html; charset=UTF-8'
        }
        echo $this->body;                             // telo; jediné echo v celej aplikácii
    }
}

Hlavičky a stavový kód musí Apache dostať skôr než telo, preto je echo posledný riadok a preto controller nič nevypisuje: iba vráti objekt a o poradie sa postará send().

S čím sa prepája: vytvára ju controller (cez render(), nižšie), prechádza Routerom späť do index.php, kde ju pošle send().

Controller

Čo to je: trieda, ktorá má na starosti jednu tabuľku. Pre každú adresu, ktorú obsluhuje, má jednu verejnú metódu; tá sa volá metóda controllera. Metóda controllera dostane objekt Request, urobí prácu pre túto adresu (vytvorí model, zavolá jeho metódu, dáta pošle view) a vráti objekt Response. Nič nevypisuje. Controller je náš kód; každý controller píše študent sám.

Kde to je: src/Controller/, jeden súbor na tabuľku. Názov: anglicky, jednotné číslo, prípona Controller; súbor má rovnaký názov s .php. Pre tabuľku categories je to src/Controller/CategoryController.php. Stránky bez tabuľky (úvod, kontrola, debug) má HomeController.php.

Čo robí: controller Jána Nováka pre číselník kategórií, celý:

src/Controller/CategoryController.php
<?php
declare(strict_types=1);

namespace App\Controller;          // trieda je v src/Controller/; autoloader ju podľa toho nájde

use App\Http\Request;
use App\Http\Response;
use App\Model\CategoryModel;

/** Číselník kategórií: zoznam. */
final class CategoryController extends BaseController   // dedí render() a notFound()
{
    // Metóda controllera pre adresu /categories. Dostane Request (dá jej ho Router), vráti Response.
    // Názov index je dohoda: index = zoznam, show = jeden záznam.
    public function index(Request $request): Response
    {
        $model = new CategoryModel();                       // objekt modelu pre túto požiadavku

        return $this->render('list', [                      // render() z BaseController
            'title' => $model->describe(),                  // 'Kategórie'
            'rows'  => $model->getAll(),                    // 4 záznamy z databázy
        ]);
    }
}

Metóda index() svoj parameter $request nepoužije; má ho aj tak, lebo Router volá každú metódu controllera rovnako, $request ako prvý parameter. Controller hlavnej entity ho používa pri vyhľadávaní.

Riadok namespace App\Controller; spolu s názvom triedy dáva celý názov App\Controller\CategoryController. Autoloader (časť „Fyzická podoba“) z neho vyrobí cestu src/Controller/CategoryController.php. Preto musí byť názov súboru presne názov triedy s .php.

S čím sa prepája: vytvorí ho Router (new CategoryController()) a zavolá jeho metódu; controller vytvorí model a zavolá getAll(); cez render() zavolá view(); vráti Response, ktorá ide cez Router do index.php.

Prečo trieda, keď doteraz to robila funkcia v index.php: Router vie triedu vytvoriť podľa názvu zapísaného v zozname adries ako text, takže index.php ostáva zoznamom a kód každej tabuľky je vo vlastnom súbore. A každý controller má dedením render() a notFound() bez toho, aby ich mal napísané.

BaseController, render() a notFound()

Čo to je: BaseController je rodič všetkých controllerov. Má metódy, ktoré potrebuje každý controller: render() vyrobí z view hotovú odpoveď, notFound() vyrobí odpoveď „Nenájdené“. Sú napísané raz, tu, a každý controller ich má cez extends BaseController. Je to náš kód. Rovnako máš v projekte BaseModel ako rodiča modelov.

Kde to je: src/Controller/BaseController.php.

src/Controller/BaseController.php
<?php
declare(strict_types=1);

namespace App\Controller;

use App\Http\Response;

/**
 * Spoločný rodič controllerov: metódy render() a notFound() vyrobia Response z view.
 * abstract: z BaseController sa objekt nevytvára, slúži len ako rodič.
 */
abstract class BaseController
{
    /**
     * Z view vyrobí hotovú odpoveď. protected: volajú ju potomkovia cez $this->render(...).
     * $this->render('list', ['title' => 'Kategórie', 'rows' => $rows]) urobí po poradí:
     *   1. view('list', [...])  spustí views/list.php a views/layout.php, vráti HTML celej stránky ako text
     *   2. new Response($html, 200)  objekt so stavovým kódom 200, hlavičkou Content-Type a HTML v tele
     *   3. tento objekt vráti; controller ho vráti ďalej (return $this->render(...))
     * Tretí parameter sa píše len vtedy, keď stavový kód nemá byť 200.
     */
    protected function render(string $view, array $data = [], int $status = 200): Response
    {
        return new Response(view($view, $data), $status);
    }

    /**
     * Odpoveď „Nenájdené“ so stavovým kódom 404: views/404.php.
     * Použije sa, keď adresa má route, ale záznam, ktorý žiada, v tabuľke nie je (/recipes/999).
     */
    protected function notFound(): Response
    {
        return $this->render('404', ['title' => 'Nenájdené'], 404);
    }
}

$this v render() je ten controller, ktorý Router vytvoril, napríklad objekt CategoryController; metódu má od BaseController.

Stránku 404 dáva aplikácia na dvoch miestach: notFound() v controlleri, keď adresa route má, ale záznam s daným číslom v tabuľke nie je (…/cv04/recipes/999); Router, keď adresa nemá route (…/cv04/nic; pojem Router nižšie).

Router a route

Čo to je: Router je trieda, ktorá má zoznam dvojíc relatívna adresa → controller a metóda controllera. Jedna dvojica v zozname sa volá route. Router pre relatívnu adresu z Request nájde route, vytvorí controller, zavolá jeho metódu a vráti jej Response. Je to náš kód.

Kde to je: src/Router.php. Zoznam route plní index.php riadkami $router->get(…).

Čo robí: route pre číselník kategórií Jána Nováka je v index.php zapísaná takto:

$router->get('/categories', [CategoryController::class, 'index']);

Čítaj: „adresu /categories má na starosti trieda CategoryController, jej metóda index.“ Pri tomto riadku controller nevzniká, dvojica sa len uloží. Keď potom index.php zavolá $router->dispatch($request), Router vezme $request->path() (/categories), v zozname nájde route s touto adresou, urobí new CategoryController() a zavolá ->index($request).

src/Router.php
<?php
declare(strict_types=1);

namespace App;

use App\Http\Request;
use App\Http\Response;

/**
 * Router: zoznam route „relatívna adresa → controller a metóda“.
 * get() pridá route, dispatch() nájde route pre Request, vytvorí controller, zavolá metódu a vráti jej Response.
 */
final class Router
{
    /** @var array<int, array{method: string, pattern: string, handler: array{0: string, 1: string}}> */
    private array $routes = [];       // zoznam route; plní ho get()

    /** Pridá route pre HTTP metódu GET. $handler je dvojica [názov triedy, názov metódy]. */
    public function get(string $path, array $handler): void
    {
        $this->add('GET', $path, $handler);
    }

    private function add(string $method, string $path, array $handler): void
    {
        // {id} v adrese nahradí (\d+): regulárny výraz, vzor pre text. \d je číslica, + je jedna
        // alebo viac, zátvorky si číslo zapamätajú.   '/recipes/{id}' → '/recipes/(\d+)'
        // Pre '/categories' sa nič nemení.
        $pattern = preg_replace('#\{[a-z_]+\}#', '(\d+)', $path);
        $this->routes[] = [
            'method'  => $method,
            'pattern' => '#^' . $pattern . '$#',   // ^ začiatok, $ koniec: '#^/categories$#'
            'handler' => $handler,
        ];
    }

    /** Nájde route pre HTTP metódu a relatívnu adresu z Requestu a vráti Response z controllera. */
    public function dispatch(Request $request): Response
    {
        foreach ($this->routes as $route) {
            if ($route['method'] !== $request->method()) {
                continue;                                     // iná HTTP metóda → ďalšia route
            }
            // preg_match() porovná vzor route s relatívnou adresou:
            //   '#^/categories$#'     a '/categories'    → sedí,   $m = ['/categories']
            //   '#^/categories$#'     a '/categories/5'  → nesedí  ($ žiada koniec hned za categories)
            //   '#^/recipes/(\d+)$#'  a '/recipes/3'     → sedí,   $m = ['/recipes/3', '3']
            //   '#^/recipes/(\d+)$#'  a '/recipes/abc'   → nesedí  (\d+ žiada číslice)
            if (preg_match($route['pattern'], $request->path(), $m)) {
                array_shift($m);                              // zahodí celú adresu: ['3'] alebo []
                $params = array_map('intval', $m);            // text na číslo: [3] alebo []
                $class  = $route['handler'][0];               // 'App\Controller\CategoryController'
                $action = $route['handler'][1];               // 'index'
                $controller = new $class();                   // tu vzniká controller
                return $controller->$action($request, ...$params);   // = $controller->index($request)
            }
        }

        // Žiadna route nesedí (/nic): Router sám vráti stránku 404.
        return new Response(view('404', ['title' => 'Nenájdené']), 404);
    }
}

new $class() vytvorí objekt triedy, ktorej názov je v premennej ako text; autoloader podľa názvu načíta src/Controller/CategoryController.php. $controller->$action(…) zavolá metódu, ktorej názov je v premennej. ...$params rozloží pole na jednotlivé parametre: pre /recipes/3 je to $controller->show($request, 3). Z PHP používa preg_replace(), preg_match(), array_shift(), array_map(), intval().

S čím sa prepája: index.php ho vytvorí, naplní cez get() a zavolá dispatch(); Router číta Request, vytvára controller a volá jeho metódu; Response z controllera podá späť do index.php.

::class

Čo to je: konštanta class, ktorú má v PHP každá trieda automaticky. Obsahuje celý názov triedy ako text.

Čo robí: echo CategoryController::class; vypíše App\Controller\CategoryController. Preto sa v route píše [CategoryController::class, 'index']: Router dostane text s názvom triedy a new $class() z neho vytvorí objekt. Zápis CategoryController::class funguje len vtedy, keď je v index.php riadok use App\Controller\CategoryController;; bez use sa píše celý názov \App\Controller\CategoryController::class. Výhoda oproti textu v úvodzovkách 'App\Controller\CategoryController': pri preklepe v názve editor podčiarkne chybu hneď.

Parameter adresy

Čo to je: dvojica názov=hodnota za otáznikom v adrese. V …/cv04/recipes?q=tofu je parameter q s hodnotou tofu. Viac parametrov sa oddeľuje &: ?q=tofu&page=2.

Kde ho dostane PHP: Apache ho dá do $_GET: $_GET['q'] je 'tofu'. Request::fromGlobals() dá celé $_GET do objektu a controller ho číta $request->query('q'). Do relatívnej adresy parameter nepatrí: $request->path() je /recipes, Router ho nevidí.

Odkiaľ sa do adresy dostane: napísaním do riadka s adresou, alebo z formulára s method="get": pole <input name="q"> s textom tofu dá po odoslaní adresu …/recipes?q=tofu. Formulár je v časti „Ako to funguje“ pri vyhľadávaní.

S čím sa prepája: $_GET → Request::query() → metóda controllera → metóda modelu search() (nižšie).

LIKE

Čo to je: operátor SQL, ktorý porovná text so vzorom. Vo vzore znamená % „ľubovoľný text, aj prázdny“. title LIKE '%tofu%' sedí na každý názov, v ktorom je tofu kdekoľvek. Pri porovnávaní utf8mb4_unicode_ci (tak sú vytvorené tvoje tabuľky) nerozlišuje veľké a malé písmená.

Kde ho použiješ: v novej metóde search() modelu hlavnej entity. Píšeš ju ty; vo vzore v src/Model/RecipeModel.php:

src/Model/RecipeModel.php
    // Recepty, ktorých názov obsahuje hľadaný text, aj s názvom obtiažnosti.
    public function search(string $q): array
    {
        $sql = "SELECT r.*, d.name AS difficulty_name
                FROM recipes r
                JOIN difficulties d ON d.id = r.difficulty_id     -- rovnaký JOIN ako v getAll()
                WHERE r.title LIKE :q                            -- :q sa dosadí v execute()
                ORDER BY r.id DESC";
        $stmt = $this->pdo->prepare($sql);                       // prepare() a execute(): hodnota od
        $stmt->execute([':q' => '%' . $q . '%']);                // používateľa ide cez parameter; '%tofu%'
        return $stmt->fetchAll();                                // pole záznamov ako z getAll()
    }

V tvojom modeli napíšeš do WHERE svoj stĺpec s názvom namiesto r.title, a JOIN taký, aký má tvoje getAll().

Čo search() vráti na dátach vzoru:

$model->search('tofu');      // WHERE r.title LIKE '%tofu%'     → 1 záznam: id 2, 'Tofu na sójovej omáčke s ryžou'
$model->search('POLIEVKA');  // WHERE r.title LIKE '%POLIEVKA%' → 1 záznam: id 1, 'Šošovicová polievka s kokosovým mliekom'
$model->search('o');         // WHERE r.title LIKE '%o%'        → všetky 4 záznamy, poradie id 4, 3, 2, 1
$model->search('pizza');     // WHERE r.title LIKE '%pizza%'    → [] prázdne pole

Apache

What it is: a program on the server sigma.tuke.sk that receives requests from browsers and sends back responses. It runs all the time; you do not start or configure it, it belongs to the server administrator. There is no Apache in Kubeflow, so a page is always tested at sigma.tuke.sk/student/….

What it does: when a request for https://sigma.tuke.sk/student/jan.novak/it/cv04/categories arrives, Apache takes the path /student/jan.novak/it/cv04/categories, turns it into a place on disk (/student/jan.novak/ is Ján Novák’s public_html folder) and looks there for the file it/cv04/categories. When it finds an ordinary file (image, CSS), it sends it to the browser as it is. When it finds a .php file, it runs it and sends the browser what PHP printed. When it finds nothing, it follows the file .htaccess (below); when that does not say otherwise either, it sends a “404 Not Found” response.

What it connects to: the browser (gets the request, returns the response), .htaccess (rules for the folder) and PHP (runs index.php and fills its $_SERVER array).

Request and response

What it is: a conversation between the browser and the server always has two steps. The browser sends a request, Apache returns a response. One request, one response. The rules of this conversation are called HTTP.

What is in the request: when Ján Novák types the address and presses Enter, the browser builds and sends this text:

GET /student/jan.novak/it/cv04/categories HTTP/1.1
Host: sigma.tuke.sk

GET is the HTTP method: the kind of request, “give me the page”. The browser uses it for an address typed into the bar, for a click on a link and for a form with method="get". After it comes the path: the part of the address after the server name. Host is the server name.

What is in the response:

HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8

<!doctype html>
<html lang="sk"> …

The first line has the status code: a number saying how the request went; 200 means “here is the page”, 404 means “I have no page for this path”. The line Content-Type: … is a header: information for the browser, here “the body is HTML in UTF-8”. After the empty line comes the body: the HTML the browser displays.

What it connects to: in our application the request is represented by the Request object and the response by the Response object (terms below); PHP writes the status code and headers with the functions http_response_code() and header(), the body with echo. You can see the whole request and response in the browser: F12 → Network tab → F5 → click the first row → Headers tab.

.htaccess

What it is: a text file named exactly .htaccess (dot at the start, no extension) with settings for Apache. It applies to the folder it lies in and to all its subfolders. Each line is one command for Apache; such a command is called a directive.

Where it is: in the application root, next to index.php: in Kubeflow ~/web/it/cv04/.htaccess, on sigma.tuke.sk public_html/it/cv04/.htaccess, on GitHub in the repository. Linux treats it as a hidden file: ls -a shows it in the terminal, the Explorer in VS Code shows it greyed.

When it is used: Apache on sigma.tuke.sk reads it on every request into this folder. You save the file in Kubeflow, SFTP transfers it, and the next request already follows the new content; nothing restarts. A typo in a directive name means status code 500 for every address in the folder until you fix it.

What it does: the whole .htaccess of your application; you have it from cv03 unchanged:

.htaccess
# 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]

What each directive does:

  • Line 2, RedirectMatch 404 …: for a path containing /src/, /vendor/, /sql/ or /.git/ it returns status code 404 even if the file exists. …/cv04/src/Router.php → 404; the code stays on the server but cannot be read from the browser.
  • Lines 5–7, <Files "config.php"> Require all denied: the file config.php cannot be opened from the browser (status code 403); PHP loads it normally. …/cv04/config.php → 403; the database password stays hidden.
  • Line 10, IndexIgnore *: a folder without index.php does not list its files. …/cv04/views/ → an empty page instead of a file list.
  • Line 13, RewriteEngine On: turns path rewriting on; without this line Apache ignores lines 14 and 15.
  • Line 14, RewriteCond %{REQUEST_FILENAME} !-f: a condition for the following rule. %{REQUEST_FILENAME} is the file on disk that corresponds to the request path: for …/cv04/categories it is public_html/it/cv04/categories, for …/cv04/css/style.css it is public_html/it/cv04/css/style.css. !-f means “it is not an existing file”. public_html/it/cv04/categories does not exist → the condition holds → line 15 runs index.php. public_html/it/cv04/css/style.css exists → the condition does not hold → Apache sends the file as it is.
  • Line 15, RewriteRule ^ index.php [L]: the rule: if the condition holds, serve the request with the file index.php. ^ matches every path, [L] means “last rule”. The original path is kept for PHP. …/cv04/categories → Apache runs index.php; …/cv04/recipes/3 → also index.php.

Lines 13–15 are the reason the application has addresses like …/categories and …/recipes/3 without .php and without ?id=: every such address ends up in the single file index.php, which decides by the path what to show.

What it connects to: Apache (reads it) and index.php (lines 13–15 send every address that is not a file there).

$_SERVER and $_GET

What it is: arrays that PHP receives already filled on every request. Apache fills them from the request text before it runs index.php. They are available in every file of the application without require and without a parameter.

What is in them for the request GET /student/jan.novak/it/cv04/categories:

$_SERVER['REQUEST_METHOD'] = 'GET';                                  // first word of the request
$_SERVER['REQUEST_URI']    = '/student/jan.novak/it/cv04/categories'; // path, including anything after '?'
$_SERVER['SCRIPT_NAME']    = '/student/jan.novak/it/cv04/index.php';  // file Apache ran
$_GET = [];                                                          // name=value pairs after '?'; none here

For the address …/cv04/recipes?q=tofu it would be $_GET = ['q' => 'tofu'].

What it connects to: in our application a single place reads them, the method Request::fromGlobals() (term Request below). $_SERVER and $_GET are written nowhere else.

index.php

What it is: the only PHP file Apache runs. All other files (src/, views/) run only because index.php loads them directly or indirectly. Such a file is called a front controller: one entrance into the application.

Where it is: the application root, ~/web/it/cv04/index.php.

What it does: on every request, in this order: loads config.php and turns on error display; loads vendor/autoload.php so that PHP finds our classes; builds a Request object from $_SERVER and $_GET; fills the list of addresses in the Router; processes the request and sends the response. The whole file is in the part “How it works”, line by line.

What it connects to: Apache runs it (line 15 of .htaccess); it creates Request and Router; the Router calls a controller; index.php finally sends the Response.

MVC

What it is: a way of splitting application code into groups by what the code does. The name is from the first letters of the groups: Model, View, Controller. Trygve Reenskaug proposed it in 1979 for programs with a graphical interface; today it is the usual structure of web applications in PHP and other languages.

What it is for: every kind of code has its place. Whoever knows it knows where to look even in someone else’s project: a database query in a model, HTML in a view, the decision “what to do for this address” in a controller. When the categories page does not work, you open CategoryController.php; when the table is sorted wrong, you open CategoryModel.php; when the HTML is wrong, you open views/list.php.

Group What it does Folder In your project
Model reads and writes the data of one table in the database src/Model/ you have it since cv02
View builds the HTML of one page from the values it receives views/ you have it since cv03
Controller for one address creates a model, calls its method and passes the data to a view src/Controller/ added today

What it connects to: the Controller calls the Model and the View; the Model knows nothing about the View or the Controller; the View receives ready values and computes nothing. Who calls whom is in the part “How it works”.

Model

What it is: a class that works with one table in the database. For every table except pivot tables there is one file with one class. It is our code.

Where it is: src/Model/, for example Ján Novák’s src/Model/CategoryModel.php for the table categories:

src/Model/CategoryModel.php
<?php
declare(strict_types=1);

namespace App\Model;

class CategoryModel extends BaseModel        // inherits getAll(), getById(), getCount() and the constructor
{
    protected string $table = 'categories';  // the table this model works with

    public function describe(): string
    {
        return 'Kategórie';                  // heading for the page
    }
}

What it does: the class extends BaseModel (src/Model/BaseModel.php), which has ready methods for every table. What they return for categories:

$model = new CategoryModel();
$model->getAll();     // [['id' => 1, 'name' => 'polievka'], ['id' => 2, 'name' => 'hlavné jedlo'],
                      //  ['id' => 3, 'name' => 'dezert'],   ['id' => 4, 'name' => 'raňajky']]
$model->getById(3);   // ['id' => 3, 'name' => 'dezert'];  for an id not in the table: null
$model->getCount();   // 4
$model->describe();   // 'Kategórie'

The model takes its database connection in the BaseModel constructor through Database::getInstance() (src/Database.php). Database is a singleton: it creates the connection once, on the first call, and then returns the same one. It connects from PHP on sigma.tuke.sk to the database on the same server. From PHP it uses the class PDO.

What it connects to: the database (through PDO) and the controller, which creates it (new CategoryModel()) and calls its method. The model does not know who calls it or what happens to the data.

View

What it is: a PHP file in the folder views/ that contains the HTML of one page and prints the values it received at marked places. It computes nothing and does not touch the database. It is our code.

Where it is: views/. For the categories lookup views/list.php (table of records) and views/layout.php (shared frame of every page: <html>, <head>, menu, heading) are used.

What it does: views/list.php receives the variables $title and $rows and builds an HTML table from them; for Ján Novák’s four categories the result is a <table> with four rows and the columns id and name. views/layout.php receives $title and $content (the finished HTML from list.php) and puts them into the page frame.

Nobody runs a file in views/ directly. The function view() in src/helpers.php, our code, runs it:

src/helpers.php
/** Builds the page HTML: loads views/<name>.php, puts the result into views/layout.php and returns it as text. */
function view(string $name, array $data = []): string
{
    // ['title' => 'Kategórie', 'rows' => [...]]  →  $title = 'Kategórie'; $rows = [...]
    extract($data);

    // views/list.php prints HTML (<?= ... ?>) as if it went straight to the browser.
    // ob_start() captures the output: from now on nothing is sent, everything is stored in memory.
    ob_start();
    require __DIR__ . '/../views/' . $name . '.php';     // runs views/list.php
    $content = ob_get_clean();                            // returns the captured text, stops capturing
    // $content = '<p>Počet záznamov: 4</p><table>...</table>'

    // The same with views/layout.php, which has <?= $content ?> in its place.
    ob_start();
    require __DIR__ . '/../views/layout.php';
    return ob_get_clean();                                // '<!doctype html>...the whole page...</html>'
}

view('list', ['title' => 'Kategórie', 'rows' => $rows]) does this: it makes the variables $title and $rows from the array (extract(), from PHP), runs views/list.php and captures its output into text (ob_start() and ob_get_clean(), from PHP), does the same with views/layout.php, and returns the HTML of the whole page as one text. It prints nothing.

What it connects to: the controller calls view() through render() (term Controller below); the controller prepares the values for the view from the model’s data; the HTML that view() returns goes into the Response object.

Request

What it is: an object that represents one request from the browser. It holds the HTTP method, the prefix, the relative address and the values after ?, i.e. everything the application needs to know about the request. The class Request is our code.

Where it is: src/Http/Request.php. The folder Http is new; it is called that because Request and Response are the two sides of the HTTP conversation.

What it does: on every request one object is created, in index.php by the line $request = Request::fromGlobals();. fromGlobals() reads $_SERVER and $_GET and stores the values in the object. For Ján Novák’s address …/cv04/categories:

$request->method();     // 'GET'                         HTTP method
$request->prefix();     // '/student/jan.novak/it/cv04'  prefix: the part of the path that is the same in all
                        //                               of Ján Novák's addresses; different for every student
$request->path();       // '/categories'                 relative address: path without prefix; the Router uses it
$request->query('q');   // ''                            value of the parameter q after '?'; nothing after '?' here

The whole file:

src/Http/Request.php
<?php
declare(strict_types=1);

namespace App\Http;

/**
 * Request: the browser request as an object. The values Apache put into $_SERVER and $_GET
 * are here as properties with methods to read them. Created once per request, in index.php, via fromGlobals().
 */
final class Request
{
    // Properties are private: written once in the constructor, then only read through methods.
    private string $method;   // 'GET'
    private string $prefix;   // '/student/jan.novak/it/cv04'
    private string $path;     // '/categories'
    private array  $query;    // ['q' => 'tofu']

    public function __construct(string $method, string $prefix, string $path, array $query)
    {
        $this->method = $method;
        $this->prefix = $prefix;
        $this->path   = $path;
        $this->query  = $query;
    }

    /**
     * Builds a Request from the arrays $_SERVER and $_GET that Apache filled.
     * static: the method belongs to the class, it is called without an object as Request::fromGlobals().
     * "::" means "take from the class"; with an object you write "->". Same as Database::getInstance().
     */
    public static function fromGlobals(): self
    {
        $prefix = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');       // '/student/jan.novak/it/cv04'
        $path   = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);   // '/student/jan.novak/it/cv04/categories'
        $path   = substr($path, strlen($prefix));                     // '/categories'
        $path   = '/' . trim($path, '/');                             // '/categories'  (for '.../cv04/' it is '/')

        return new self($_SERVER['REQUEST_METHOD'], $prefix, $path, $_GET);   // Request object
    }

    public function method(): string
    {
        return $this->method;
    }

    public function prefix(): string
    {
        return $this->prefix;
    }

    public function path(): string
    {
        return $this->path;
    }

    /**
     * Parameter from the address after '?'. For ?q=tofu, $this->query = ['q' => 'tofu'] and query('q') returns 'tofu'.
     * For an address without '?', $this->query = [] and query('q') returns $default, i.e. ''.
     * "??" means: if the left side does not exist, use the right one.
     */
    public function query(string $key, string $default = ''): string
    {
        return (string) ($this->query[$key] ?? $default);
    }
}

From PHP it uses $_SERVER, $_GET and the functions dirname(), rtrim(), trim(), substr(), strlen(), parse_url().

What it connects to: index.php creates it, it is passed to the Router (which reads method() and path()) and to the controller (which reads query()). In the whole application only the method fromGlobals() reads $_SERVER and $_GET.

Response

What it is: an object that represents one response for the browser: status code, headers and body. The class Response is our code.

Where it is: src/Http/Response.php.

What it does: the controller creates and returns it; index.php sends it with the method send(). For Ján Novák’s categories page the object holds status code 200, the header Content-Type: text/html; charset=UTF-8 and the body: the HTML of the whole page from the function view().

src/Http/Response.php
<?php
declare(strict_types=1);

namespace App\Http;

/**
 * Response: the response for the browser as an object: status code, headers, body.
 * The controller returns it, index.php sends it with the method send().
 */
final class Response
{
    private string $body;      // HTML
    private int    $status;    // 200, 404, ...
    private array  $headers;   // ['Content-Type' => 'text/html; charset=UTF-8']

    // new Response($html) is enough for an ordinary page: $status defaults to 200, headers are empty.
    public function __construct(string $body, int $status = 200, array $headers = [])
    {
        $this->body    = $body;
        $this->status  = $status;
        // "+" joins two arrays; for the same key the value from the left one stays.
        // [] + ['Content-Type' => 'text/html...']                 → ['Content-Type' => 'text/html...']
        // ['Content-Type' => 'text/plain'] + ['Content-Type' => 'text/html...'] → ['Content-Type' => 'text/plain']
        $this->headers = $headers + ['Content-Type' => 'text/html; charset=UTF-8'];
    }

    public function status(): int
    {
        return $this->status;
    }

    public function body(): string
    {
        return $this->body;
    }

    /**
     * Sends the response to the browser. Our method; from PHP it uses http_response_code(), header() and echo.
     * Called once, in the last line of index.php.
     */
    public function send(): void
    {
        http_response_code($this->status);            // Apache puts the number into the first line of the response
        foreach ($this->headers as $name => $value) {
            header($name . ': ' . $value);            // the line 'Content-Type: text/html; charset=UTF-8'
        }
        echo $this->body;                             // body; the only echo in the whole application
    }
}

Apache must get the headers and the status code before the body, which is why echo is the last line and why the controller prints nothing: it only returns the object and send() takes care of the order.

What it connects to: the controller creates it (through render(), below), it passes through the Router back to index.php, where send() sends it.

Controller

What it is: a class in charge of one table. For every address it serves it has one public method; this is called a controller method. A controller method receives the Request object, does the work for this address (creates a model, calls its method, passes the data to a view) and returns a Response object. It prints nothing. A controller is our code; each student writes their own controllers.

Where it is: src/Controller/, one file per table. Name: English, singular, suffix Controller; the file has the same name with .php. For the table categories it is src/Controller/CategoryController.php. Pages without a table (home, check, debug) are in HomeController.php.

What it does: Ján Novák’s controller for the categories lookup, whole:

src/Controller/CategoryController.php
<?php
declare(strict_types=1);

namespace App\Controller;          // the class is in src/Controller/; the autoloader finds it by this

use App\Http\Request;
use App\Http\Response;
use App\Model\CategoryModel;

/** Categories lookup: list. */
final class CategoryController extends BaseController   // inherits render() and notFound()
{
    // Controller method for the address /categories. Receives a Request (the Router passes it), returns a Response.
    // The name index is a convention: index = list, show = one record.
    public function index(Request $request): Response
    {
        $model = new CategoryModel();                       // model object for this request

        return $this->render('list', [                      // render() from BaseController
            'title' => $model->describe(),                  // 'Kategórie'
            'rows'  => $model->getAll(),                    // 4 records from the database
        ]);
    }
}

The method index() does not use its parameter $request; it has it anyway, because the Router calls every controller method the same way, $request as the first parameter. The main entity controller uses it for searching.

The line namespace App\Controller; together with the class name gives the full name App\Controller\CategoryController. The autoloader (part “Physical form”) turns it into the path src/Controller/CategoryController.php. That is why the file name must be exactly the class name with .php.

What it connects to: the Router creates it (new CategoryController()) and calls its method; the controller creates a model and calls getAll(); through render() it calls view(); it returns a Response, which goes through the Router to index.php.

Why a class, when a function in index.php did this until now: the Router can create the class from its name written in the address list as text, so index.php stays a list and the code of every table is in its own file. And every controller gets render() and notFound() by inheritance without having to write them.

BaseController, render() and notFound()

What it is: BaseController is the parent of all controllers. It has the methods every controller needs: render() builds a finished response from a view, notFound() builds a “Not found” response. They are written once, here, and every controller has them through extends BaseController. It is our code. In the same way your project has BaseModel as the parent of models.

Where it is: src/Controller/BaseController.php.

src/Controller/BaseController.php
<?php
declare(strict_types=1);

namespace App\Controller;

use App\Http\Response;

/**
 * Shared parent of controllers: the methods render() and notFound() build a Response from a view.
 * abstract: no object of BaseController is created, it only serves as a parent.
 */
abstract class BaseController
{
    /**
     * Builds a finished response from a view. protected: descendants call it as $this->render(...).
     * $this->render('list', ['title' => 'Kategórie', 'rows' => $rows]) does, in order:
     *   1. view('list', [...])  runs views/list.php and views/layout.php, returns the HTML of the whole page as text
     *   2. new Response($html, 200)  an object with status code 200, the Content-Type header and the HTML in the body
     *   3. returns this object; the controller returns it further (return $this->render(...))
     * The third parameter is written only when the status code should not be 200.
     */
    protected function render(string $view, array $data = [], int $status = 200): Response
    {
        return new Response(view($view, $data), $status);
    }

    /**
     * “Not found” response with status code 404: views/404.php.
     * Used when the address has a route but the record it asks for is not in the table (/recipes/999).
     */
    protected function notFound(): Response
    {
        return $this->render('404', ['title' => 'Nenájdené'], 404);
    }
}

$this in render() is the controller the Router created, for example the CategoryController object; it has the method from BaseController.

The application gives the 404 page in two places: notFound() in the controller, when the address has a route but the record with the given number is not in the table (…/cv04/recipes/999); the Router, when the address has no route (…/cv04/nic; term Router below).

Router and route

What it is: Router is a class with a list of pairs relative address → controller and controller method. One pair in the list is called a route. For the relative address from Request the Router finds the route, creates the controller, calls its method and returns its Response. It is our code.

Where it is: src/Router.php. index.php fills the route list with the lines $router->get(…).

What it does: the route for Ján Novák’s categories lookup is written in index.php like this:

$router->get('/categories', [CategoryController::class, 'index']);

Read: “the address /categories is handled by the class CategoryController, its method index.” At this line no controller is created, the pair is only stored. When index.php later calls $router->dispatch($request), the Router takes $request->path() (/categories), finds the route with this address in the list, does new CategoryController() and calls ->index($request).

src/Router.php
<?php
declare(strict_types=1);

namespace App;

use App\Http\Request;
use App\Http\Response;

/**
 * Router: list of routes “relative address → controller and method”.
 * get() adds a route, dispatch() finds the route for a Request, creates the controller, calls the method and returns its Response.
 */
final class Router
{
    /** @var array<int, array{method: string, pattern: string, handler: array{0: string, 1: string}}> */
    private array $routes = [];       // route list; get() fills it

    /** Adds a route for the HTTP method GET. $handler is the pair [class name, method name]. */
    public function get(string $path, array $handler): void
    {
        $this->add('GET', $path, $handler);
    }

    private function add(string $method, string $path, array $handler): void
    {
        // {id} in the address is replaced by (\d+): a regular expression, a pattern for text. \d is a digit,
        // + is one or more, the brackets remember the number.   '/recipes/{id}' → '/recipes/(\d+)'
        // For '/categories' nothing changes.
        $pattern = preg_replace('#\{[a-z_]+\}#', '(\d+)', $path);
        $this->routes[] = [
            'method'  => $method,
            'pattern' => '#^' . $pattern . '$#',   // ^ start, $ end: '#^/categories$#'
            'handler' => $handler,
        ];
    }

    /** Finds the route for the HTTP method and relative address from the Request and returns the controller's Response. */
    public function dispatch(Request $request): Response
    {
        foreach ($this->routes as $route) {
            if ($route['method'] !== $request->method()) {
                continue;                                     // other HTTP method → next route
            }
            // preg_match() compares the route pattern with the relative address:
            //   '#^/categories$#'     and '/categories'    → match,    $m = ['/categories']
            //   '#^/categories$#'     and '/categories/5'  → no match  ($ wants the end right after categories)
            //   '#^/recipes/(\d+)$#'  and '/recipes/3'     → match,    $m = ['/recipes/3', '3']
            //   '#^/recipes/(\d+)$#'  and '/recipes/abc'   → no match  (\d+ wants digits)
            if (preg_match($route['pattern'], $request->path(), $m)) {
                array_shift($m);                              // drops the whole address: ['3'] or []
                $params = array_map('intval', $m);            // text to number: [3] or []
                $class  = $route['handler'][0];               // 'App\Controller\CategoryController'
                $action = $route['handler'][1];               // 'index'
                $controller = new $class();                   // here the controller is created
                return $controller->$action($request, ...$params);   // = $controller->index($request)
            }
        }

        // No route matches (/nic): the Router itself returns the 404 page.
        return new Response(view('404', ['title' => 'Nenájdené']), 404);
    }
}

new $class() creates an object of the class whose name is in the variable as text; the autoloader loads src/Controller/CategoryController.php by the name. $controller->$action(…) calls the method whose name is in the variable. ...$params spreads the array into separate parameters: for /recipes/3 it is $controller->show($request, 3). From PHP it uses preg_replace(), preg_match(), array_shift(), array_map(), intval().

What it connects to: index.php creates it, fills it through get() and calls dispatch(); the Router reads the Request, creates the controller and calls its method; it hands the controller’s Response back to index.php.

::class

What it is: the constant class that every class in PHP has automatically. It contains the full class name as text.

What it does: echo CategoryController::class; prints App\Controller\CategoryController. That is why a route is written as [CategoryController::class, 'index']: the Router receives the class name as text and new $class() creates the object from it. The form CategoryController::class works only when index.php has the line use App\Controller\CategoryController;; without use you write the full name \App\Controller\CategoryController::class. The advantage over a quoted text 'App\Controller\CategoryController': with a typo in the name the editor underlines the error immediately.

Address parameter

What it is: a name=value pair after the question mark in an address. In …/cv04/recipes?q=tofu there is one parameter, q, with the value tofu. More parameters are separated by &: ?q=tofu&page=2.

Where PHP gets it: Apache puts it into $_GET: $_GET['q'] is 'tofu'. Request::fromGlobals() puts the whole $_GET into the object and the controller reads it with $request->query('q'). The parameter is not part of the relative address: $request->path() is /recipes, the Router does not see it.

How it gets into the address: by typing it into the address bar, or from a form with method="get": the field <input name="q"> with the text tofu gives the address …/recipes?q=tofu after submitting. The form is in the part “How it works”, at the search.

What it connects to: $_GET → Request::query() → controller method → model method search() (below).

LIKE

What it is: an SQL operator that compares text with a pattern. In the pattern % means “any text, even empty”. title LIKE '%tofu%' matches every title with tofu anywhere in it. With the collation utf8mb4_unicode_ci (your tables are created with it) it does not distinguish upper and lower case.

Where you use it: in the new method search() of the main entity model. You write it; in the sample it is in src/Model/RecipeModel.php:

src/Model/RecipeModel.php
    // Recipes whose title contains the searched text, with the difficulty name.
    public function search(string $q): array
    {
        $sql = "SELECT r.*, d.name AS difficulty_name
                FROM recipes r
                JOIN difficulties d ON d.id = r.difficulty_id     -- same JOIN as in getAll()
                WHERE r.title LIKE :q                            -- :q is filled in execute()
                ORDER BY r.id DESC";
        $stmt = $this->pdo->prepare($sql);                       // prepare() and execute(): the value from
        $stmt->execute([':q' => '%' . $q . '%']);                // the user goes through a parameter; '%tofu%'
        return $stmt->fetchAll();                                // array of records like getAll()
    }

In your model you write your own title column in WHERE instead of r.title, and the same JOIN your getAll() has.

What search() returns on the sample data:

$model->search('tofu');      // WHERE r.title LIKE '%tofu%'     → 1 record: id 2, 'Tofu na sójovej omáčke s ryžou'
$model->search('POLIEVKA');  // WHERE r.title LIKE '%POLIEVKA%' → 1 record: id 1, 'Šošovicová polievka s kokosovým mliekom'
$model->search('o');         // WHERE r.title LIKE '%o%'        → all 4 records, order id 4, 3, 2, 1
$model->search('pizza');     // WHERE r.title LIKE '%pizza%'    → [] empty array

Ako to funguje: kto koho voláHow it works: who calls whom

Číselník: zoznam kategórií

Čo Ján Novák chce: vidieť zoznam kategórií. Klikne v menu na Kategórie, alebo napíše https://sigma.tuke.sk/student/jan.novak/it/cv04/categories a stlačí Enter. Ideme po poradí, krok za krokom.

Krok 1. Prehliadač pošle požiadavku.

GET /student/jan.novak/it/cv04/categories 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/cv04/categories na disku nie je. V .htaccess platí:

RewriteCond %{REQUEST_FILENAME} !-f      # súbor "categories" 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/cv04/categories';
$_SERVER['SCRIPT_NAME']    = '/student/jan.novak/it/cv04/index.php';
$_GET = [];                              // v adrese nie je nič za '?'

Krok 3. Beží index.php. Celý súbor, komentáre hovoria, čo sa pri tejto požiadavke deje:

index.php
<?php
declare(strict_types=1);                 // PHP nebude ticho prevádzať typy; chyba typu sa ozve hneď

// Načíta config.php. Súbor vracia pole s údajmi k databáze a s kľúčom 'debug'.
$config = require __DIR__ . '/config.php';
if ($config['debug']) {              // debug je true →
    ini_set('display_errors', '1');  // chyby PHP sa budú vypisovať do prehliadača
    error_reporting(E_ALL);
}

// __DIR__ = priečinok, v ktorom leží tento súbor (na sigma.tuke.sk .../public_html/it/cv04).
// . '/vendor/autoload.php' = k nemu pripojí cestu k súboru, ktorý vyrobil Composer.
// require = načíta ten súbor a vykoná ho. Vo vendor/autoload.php je kód od Composeru, ktorý PHP
// povie: „keď niekto použije triedu App\Niečo a ty ju nemáš, otvor src/Niečo.php“,
// a hneď načíta src/helpers.php (funkcie e(), url(), view()).
require __DIR__ . '/vendor/autoload.php';

// Krátke názvy tried pre tento súbor (Router namiesto App\Router).
use App\Router;
use App\Http\Request;
use App\Controller\HomeController;
use App\Controller\CategoryController;
use App\Controller\RecipeController;

// Z $_SERVER a $_GET vznikne objekt Request (krok 4).
$request = Request::fromGlobals();

// Konštanta BASE_URL = '/student/jan.novak/it/cv04'. Konštanta je pomenovaná hodnota dostupná
// v každom súbore bez parametra; číta ju funkcia url() pri každom odkaze.
define('BASE_URL', $request->prefix());

// Prázdny zoznam route.
$router = new Router();

// Šesť route: adresa → ktorá trieda a ktorá jej metóda sa o ňu stará.
// Teraz sa len ukladajú. Žiadny controller zatiaľ nevzniká.
$router->get('/',             [HomeController::class, 'index']);
$router->get('/kontrola',     [HomeController::class, 'kontrola']);
$router->get('/debug',        [HomeController::class, 'debug']);
$router->get('/categories',   [CategoryController::class, 'index']);   // naša adresa
$router->get('/recipes',      [RecipeController::class, 'index']);
$router->get('/recipes/{id}', [RecipeController::class, 'show']);

// Router nájde route pre '/categories', zavolá controller a vráti Response (kroky 5–8).
$response = $router->dispatch($request);

// Response pošle stavový kód, hlavičku a HTML prehliadaču (krok 9).
$response->send();

Krok 4. Request::fromGlobals() vyrobí objekt $request. V src/Http/Request.php sa vykoná:

$prefix = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');     // '/student/jan.novak/it/cv04'
$path   = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // '/student/jan.novak/it/cv04/categories'
$path   = substr($path, strlen($prefix));                   // '/categories'
$path   = '/' . trim($path, '/');                           // '/categories'

return new self('GET', $prefix, $path, []);                 // objekt Request

Od teraz $request->path() vráti '/categories' a $request->method() vráti 'GET'.

Krok 5. Router::dispatch($request) hľadá route. V src/Router.php prebehne zoznam. Pri štvrtej route:

if (preg_match('#^/categories$#', '/categories', $m)) {    // vzor route a $request->path(): sedí
    array_shift($m);                                        // $m bolo ['/categories'], teraz []
    $params = array_map('intval', $m);                      // []  – žiadne číslo z adresy
    $class  = 'App\Controller\CategoryController';          // z dvojice: názov triedy
    $action = 'index';                                      // z dvojice: názov metódy
    $controller = new $class();                             // vznikne objekt CategoryController
    return $controller->$action($request, ...$params);      // = $controller->index($request)
}

Router zavolal metódu index() controllera a čaká, čo mu vráti.

Krok 6. CategoryController::index($request) robí prácu pre túto adresu. V src/Controller/CategoryController.php:

public function index(Request $request): Response
{
    $model = new CategoryModel();                        // objekt modelu (krok 7)

    return $this->render('list', [                       // render() z BaseController (krok 8)
        'title' => $model->describe(),                   // 'Kategórie'
        'rows'  => $model->getAll(),                     // 4 záznamy z databázy (krok 7)
    ]);
}

Krok 7. Model siahne do databázy. new CategoryModel() spustí konštruktor, ktorý CategoryModel zdedil od BaseModel (src/Model/BaseModel.php):

public function __construct()
{
    $this->pdo = Database::getInstance();   // pripojenie k databáze: objekt PDO
}

Database je singleton: getInstance() vytvorí objekt PDO pri prvom zavolaní, pri každom ďalšom vráti ten istý. Celá aplikácia má jedno pripojenie.

$model->getAll() v BaseModel:

public function getAll(): array
{
    // {$this->table} = 'categories' → "SELECT * FROM categories ORDER BY id"
    return $this->pdo->query("SELECT * FROM {$this->table} ORDER BY id")->fetchAll();
}

Vráti:

[
    ['id' => 1, 'name' => 'polievka'],
    ['id' => 2, 'name' => 'hlavné jedlo'],
    ['id' => 3, 'name' => 'dezert'],
    ['id' => 4, 'name' => 'raňajky'],
]

$model->describe() vráti 'Kategórie'.

Krok 8. render() vyrobí Response. V src/Controller/BaseController.php:

protected function render(string $view, array $data = [], int $status = 200): Response
{
    // view('list', ['title' => 'Kategórie', 'rows' => [...4 záznamy...]])
    //   spustí views/list.php  → <p>Počet záznamov: 4</p><table>...</table>
    //   spustí views/layout.php → <!doctype html>...celá stránka...</html>
    //   a vráti to ako jeden text.
    // new Response(ten text, 200) → objekt so stavovým kódom 200, hlavičkou a HTML.
    return new Response(view($view, $data), $status);
}

Objekt Response sa vracia naspäť tou istou cestou, akou šlo volanie: render() ho vráti do index(), index() ho vráti do dispatch(), dispatch() ho vráti do index.php, kde sa uloží do $response.

Krok 9. $response->send() pošle odpoveď. V src/Http/Response.php:

public function send(): void
{
    http_response_code(200);                                  // prvý riadok odpovede: 200 OK
    header('Content-Type: text/html; charset=UTF-8');         // hlavička
    echo $this->body;                                         // HTML celej stránky
}

(V skutočnom súbore je hlavička v cykle foreach, lebo ich môže byť viac; pre našu odpoveď je jedna.)

Krok 10. Prehliadač zobrazí stránku. Apache k tomu, čo PHP vypísalo, dopíše prvý riadok HTTP/1.1 200 OK a odošle. Prehliadač zobrazí menu, nadpis Kategórie, text Počet záznamov: 4 a tabuľku:

id | name
1  | polievka
2  | hlavné jedlo
3  | dezert
4  | raňajky

Hlavná entita: čo človek chce a ako to aplikácia urobí

Pri tabuľke recipes chce Ján Novák v prehliadači robiť tieto veci:

  • pozrieť si zoznam všetkých receptov – klikne v menu na Recepty; adresa …/cv04/recipes
  • otvoriť jeden recept – klikne v zozname na jeho číslo; adresa …/cv04/recipes/3
  • nájsť recepty, ktoré majú v názve nejaké slovo – napíše slovo do poľa nad zoznamom a klikne na Hľadať; adresa …/cv04/recipes?q=tofu

Všetky tri požiadavky obsluhuje jeden controller, RecipeController. Zoznam a hľadanie sú tá istá stránka, len s vyplneným alebo prázdnym poľom, preto ich robí tá istá metóda index(). Detail robí metóda show(). V index.php je to zapísané takto:

$router->get('/recipes',      [RecipeController::class, 'index']);   // zoznam; s ?q= aj hľadanie
$router->get('/recipes/{id}', [RecipeController::class, 'show']);    // jeden recept podľa čísla

Controller src/Controller/RecipeController.php, celý:

src/Controller/RecipeController.php
<?php
declare(strict_types=1);

namespace App\Controller;

use App\Http\Request;
use App\Http\Response;
use App\Model\RecipeModel;

final class RecipeController extends BaseController
{
    // Adresa /recipes a /recipes?q=tofu
    public function index(Request $request): Response
    {
        $model = new RecipeModel();
        $q     = $request->query('q');          // pre /recipes → '';  pre /recipes?q=tofu → 'tofu'
        $rows  = $q === ''                      // nič sa nehľadá?
            ? $model->getAll()                  // → všetky recepty
            : $model->search($q);               // → len recepty s 'tofu' v názve

        return $this->render('list', [
            'title' => $model->describe(),      // 'Recepty'
            'rows'  => $rows,
            'show'  => '/recipes',              // list.php z toho urobí odkaz v stĺpci id: /recipes/3
            'q'     => $q,                      // list.php vráti hľadaný text do poľa formulára
        ]);
    }

    // Adresa /recipes/3: Router dá do $id číslo z adresy
    public function show(Request $request, int $id): Response
    {
        $model = new RecipeModel();
        $row   = $model->getById($id);          // pre 3 → pole so záznamom; pre 999 → null
        if ($row === null) {
            return $this->notFound();           // stránka „Nenájdené“, stavový kód 404
        }

        return $this->render('show', [
            'title' => $row['title'],           // 'Tofu na sójovej omáčke s ryžou'
            'row'   => $row,
            'back'  => '/recipes',              // show.php z toho urobí odkaz „Späť na zoznam“
        ]);
    }
}

Ján Novák chce otvoriť recept číslo 3

Klikne v zozname na číslo 3. Prehliadač pošle požiadavku na …/cv04/recipes/3. Kroky 1–4 sú rovnaké ako pri číselníku; $request->path() je '/recipes/3'. Router prejde zoznam, pri šiestej route:

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
    $class  = 'App\Controller\RecipeController';
    $action = 'show';
    $controller = new $class();
    return $controller->$action($request, ...$params);      // = $controller->show($request, 3)
}

show($request, 3) zavolá $model->getById(3); v RecipeModel sa pošle dotaz s WHERE r.id = 3 a vráti sa jeden záznam ako pole: ['id' => 3, 'title' => '…', 'servings' => 4, …, 'difficulty_name' => 'ľahký']. render('show', …) spustí views/show.php (vypíše záznam ako zoznam dvojíc stĺpec–hodnota) a views/layout.php, vráti Response so stavovým kódom 200. Ďalej ako kroky 8–10.

Pre …/cv04/recipes/999 je všetko rovnaké až po getById(999), ktoré vráti null. Controller vráti $this->notFound():

protected function notFound(): Response
{
    return $this->render('404', ['title' => 'Nenájdené'], 404);   // views/404.php, stavový kód 404
}

Prehliadač zobrazí stránku „Nenájdené“ a v karte Network je stavový kód 404.

Ján Novák chce nájsť recepty so slovom „tofu“ v názve

Potrebuje na stránke pole, do ktorého slovo napíše, a tlačidlo. To je formulár vo views/list.php; po kliknutí z neho vznikne adresa …/cv04/recipes?q=tofu. Formulár je na začiatku views/list.php; píše ho študent, zvyšok súboru má z cv03:

views/list.php
<?php /* Očakáva: $rows, voliteľne $show (adresa detailu) a $q (hľadaný text). */ ?>
<?php if (isset($q)): ?>                             <!-- controller poslal $q → formulár sa zobrazí;
                                                          číselníky $q neposielajú → bez formulára -->
    <form method="get" action="<?= url($show) ?>">   <!-- action = /student/jan.novak/it/cv04/recipes -->
        <input type="text" name="q" value="<?= e($q) ?>" placeholder="Hľadať v názve">
        <button type="submit">Hľadať</button>
        <a href="<?= url($show) ?>">Zrušiť</a>        <!-- zoznam bez hľadania -->
    </form>
<?php endif; ?>
<?php if (!$rows): ?>
    <p>Žiadne záznamy.</p>
<?php else: ?>

Funkcie url() a e() sú v src/helpers.php:

src/helpers.php
// Z relatívnej adresy vyrobí celú cestu pre href.
// url('/recipes') → '/student/jan.novak/it/cv04/recipes'
function url(string $path): string
{
    return BASE_URL . '/' . ltrim($path, '/');     // BASE_URL je z index.php
}

// Text pre výpis do HTML: znaky < > & " sa zobrazia ako znaky, nie ako HTML.
// e('<b>tofu</b>') → '&lt;b&gt;tofu&lt;/b&gt;'  – prehliadač ukáže <b>tofu</b> ako text
function e(?string $text): string
{
    return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8');
}

Ján Novák napíše do poľa tofu a klikne na Hľadať. Prehliadač zostaví adresu z action a z poľa (name="q", hodnota tofu):

GET /student/jan.novak/it/cv04/recipes?q=tofu HTTP/1.1

Je to tá istá požiadavka, ako keby adresu napísal rukou. Apache dá do $_GET:

$_GET = ['q' => 'tofu'];

Aplikácia hľadá recepty so slovom „tofu“

Prehliadač poslal …/cv04/recipes?q=tofu. Aplikácia potrebuje z databázy vybrať recepty, ktorých názov obsahuje tofu; v SQL sa to povie WHERE r.title LIKE '%tofu%'. Ako sa k tomu dostane od požiadavky po dotaz:

Request::fromGlobals() dá $path = '/recipes' (časť za ? do cesty nepatrí) a $query = ['q' => 'tofu']. Router nájde route /recipes a zavolá index($request). V index():

$q    = $request->query('q');     // 'tofu'
$rows = $model->search('tofu');   // v RecipeModel (pojem LIKE): 1 záznam, id 2

render('list', ['title' => 'Recepty', 'rows' => 1 záznam, 'show' => '/recipes', 'q' => 'tofu']) spustí views/list.php: formulár má v poli tofu (riadok value="<?= e($q) ?>"), pod ním tabuľka s jedným receptom. Ďalej ako kroky 8–10.

Zoznam receptov s vyhľadávaním
…/cv04/recipes?q=tofu vo vzorovej aplikácii: pole s textom tofu, pod ním tabuľka s jedným receptom.

Debug stránka: keď niečo nefunguje

Čo Ján Novák chce: napísal …/cv04/kategorie a dostal stránku „Nenájdené“, hoci je presvedčený, že zoznam kategórií má. Chce vidieť, čo aplikácia z jeho adresy urobila, aby našiel chybu.

Ako mu aplikácia pomôže: otvorí …/cv04/debug, potom koniec adresy zmení na to, čo nefungovalo. Stránka vypíše, čo Apache dal do $_SERVER a čo z toho Request vypočítal. Pre …/cv04/kategorie uvidí v riadku $request->path() hodnotu /kategorie; v index.php má route /categories. Preklep je nájdený. Pre …/cv04/debug?q=tofu uvidí v poslednom riadku tofu, teda parameter z adresy dorazil.

Route v index.php:

$router->get('/debug', [HomeController::class, 'debug']);

Metóda v src/Controller/HomeController.php:

public function debug(Request $request): Response
{
    return $this->render('debug', ['title' => 'Debug', 'request' => $request]);  // view dostane celý objekt
}

View views/debug.php:

views/debug.php
<?php /* Očakáva: $request (objekt App\Http\Request). */ ?>
<table>
    <!-- čo dal Apache do $_SERVER -->
    <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>
    <!-- čo z toho vypočítal Request -->
    <tr><th>$request->method()</th>  <td><?= e($request->method()) ?></td></tr>
    <tr><th>$request->prefix()</th>  <td><?= e($request->prefix()) ?></td></tr>
    <tr><th>$request->path()</th>    <td><?= e($request->path()) ?></td></tr>
    <tr><th>$request->query('q')</th><td><?= e($request->query('q')) ?></td></tr>
</table>
<p>Zmeň koniec adresy, napríklad na <code>/debug?q=tofu</code>, a sleduj, čo sa v tabuľke zmení.</p>

Čo stránka ukáže pre …/cv04/debug?q=tofu:

$_SERVER['REQUEST_METHOD']   GET
$_SERVER['SCRIPT_NAME']      /student/jan.novak/it/cv04/index.php
$_SERVER['REQUEST_URI']      /student/jan.novak/it/cv04/debug?q=tofu
$request->method()           GET
$request->prefix()           /student/jan.novak/it/cv04
$request->path()             /debug                       ← bez ?q=tofu
$request->query('q')         tofu

Celý HomeController.php, aby bolo vidieť, kde sú úvod, kontrola a debug:

src/Controller/HomeController.php
<?php
declare(strict_types=1);

namespace App\Controller;

use App\Http\Request;
use App\Http\Response;

/** Stránky bez tabuľky: úvod, kontrola, debug. Sem pridáš aj svoju stránku /o-aplikacii (úloha 5.5). */
final class HomeController extends BaseController
{
    public function index(Request $request): Response
    {
        return $this->render('home', ['title' => 'Úvod']);                   // views/home.php
    }

    public function kontrola(Request $request): Response
    {
        return $this->render('kontrola', ['title' => 'Kontrola projektu']);  // views/kontrola.php
    }

    public function debug(Request $request): Response
    {
        return $this->render('debug', ['title' => 'Debug', 'request' => $request]);  // views/debug.php
    }
}

Lookup table: list of categories

What Ján Novák wants: to see the list of categories. He clicks Kategórie in the menu, or types https://sigma.tuke.sk/student/jan.novak/it/cv04/categories and presses Enter. We go step by step.

Step 1. The browser sends a request.

GET /student/jan.novak/it/cv04/categories 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/cv04/categories is not on disk. In .htaccess this applies:

RewriteCond %{REQUEST_FILENAME} !-f      # the file "categories" 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/cv04/categories';
$_SERVER['SCRIPT_NAME']    = '/student/jan.novak/it/cv04/index.php';
$_GET = [];                              // nothing after '?' in the address

Step 3. index.php runs. The whole file; the comments say what happens for this request:

index.php
<?php
declare(strict_types=1);                 // PHP will not silently convert types; a type error is reported at once

// Loads config.php. The file returns an array with the database data and the key 'debug'.
$config = require __DIR__ . '/config.php';
if ($config['debug']) {              // debug is true →
    ini_set('display_errors', '1');  // PHP errors will be printed into the browser
    error_reporting(E_ALL);
}

// __DIR__ = the folder this file lies in (on sigma.tuke.sk .../public_html/it/cv04).
// . '/vendor/autoload.php' = appends the path to the file Composer produced.
// require = loads that file and runs it. vendor/autoload.php contains code from Composer that tells PHP:
// “when someone uses the class App\Something and you do not have it, open src/Something.php”,
// and loads src/helpers.php right away (functions e(), url(), view()).
require __DIR__ . '/vendor/autoload.php';

// Short class names for this file (Router instead of App\Router).
use App\Router;
use App\Http\Request;
use App\Controller\HomeController;
use App\Controller\CategoryController;
use App\Controller\RecipeController;

// From $_SERVER and $_GET a Request object is created (step 4).
$request = Request::fromGlobals();

// Constant BASE_URL = '/student/jan.novak/it/cv04'. A constant is a named value available
// in every file without a parameter; the function url() reads it for every link.
define('BASE_URL', $request->prefix());

// Empty route list.
$router = new Router();

// Six routes: address → which class and which of its methods handles it.
// They are only stored now. No controller is created yet.
$router->get('/',             [HomeController::class, 'index']);
$router->get('/kontrola',     [HomeController::class, 'kontrola']);
$router->get('/debug',        [HomeController::class, 'debug']);
$router->get('/categories',   [CategoryController::class, 'index']);   // our address
$router->get('/recipes',      [RecipeController::class, 'index']);
$router->get('/recipes/{id}', [RecipeController::class, 'show']);

// The Router finds the route for '/categories', calls the controller and returns a Response (steps 5–8).
$response = $router->dispatch($request);

// The Response sends the status code, header and HTML to the browser (step 9).
$response->send();

Step 4. Request::fromGlobals() builds the object $request. In src/Http/Request.php this runs:

$prefix = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');     // '/student/jan.novak/it/cv04'
$path   = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // '/student/jan.novak/it/cv04/categories'
$path   = substr($path, strlen($prefix));                   // '/categories'
$path   = '/' . trim($path, '/');                           // '/categories'

return new self('GET', $prefix, $path, []);                 // Request object

From now on $request->path() returns '/categories' and $request->method() returns 'GET'.

Step 5. Router::dispatch($request) looks for a route. In src/Router.php the list is walked. At the fourth route:

if (preg_match('#^/categories$#', '/categories', $m)) {    // route pattern and $request->path(): match
    array_shift($m);                                        // $m was ['/categories'], now []
    $params = array_map('intval', $m);                      // []  – no number from the address
    $class  = 'App\Controller\CategoryController';          // from the pair: class name
    $action = 'index';                                      // from the pair: method name
    $controller = new $class();                             // a CategoryController object is created
    return $controller->$action($request, ...$params);      // = $controller->index($request)
}

The Router called the controller’s method index() and waits for what it returns.

Step 6. CategoryController::index($request) does the work for this address. In src/Controller/CategoryController.php:

public function index(Request $request): Response
{
    $model = new CategoryModel();                        // model object (step 7)

    return $this->render('list', [                       // render() from BaseController (step 8)
        'title' => $model->describe(),                   // 'Kategórie'
        'rows'  => $model->getAll(),                     // 4 records from the database (step 7)
    ]);
}

Step 7. The model reaches into the database. new CategoryModel() runs the constructor that CategoryModel inherited from BaseModel (src/Model/BaseModel.php):

public function __construct()
{
    $this->pdo = Database::getInstance();   // database connection: a PDO object
}

Database is a singleton: getInstance() creates the PDO object on the first call and returns the same one on every later call. The whole application has one connection.

$model->getAll() in BaseModel:

public function getAll(): array
{
    // {$this->table} = 'categories' → "SELECT * FROM categories ORDER BY id"
    return $this->pdo->query("SELECT * FROM {$this->table} ORDER BY id")->fetchAll();
}

Returns:

[
    ['id' => 1, 'name' => 'polievka'],
    ['id' => 2, 'name' => 'hlavné jedlo'],
    ['id' => 3, 'name' => 'dezert'],
    ['id' => 4, 'name' => 'raňajky'],
]

$model->describe() returns 'Kategórie'.

Step 8. render() builds the Response. In src/Controller/BaseController.php:

protected function render(string $view, array $data = [], int $status = 200): Response
{
    // view('list', ['title' => 'Kategórie', 'rows' => [...4 records...]])
    //   runs views/list.php   → <p>Počet záznamov: 4</p><table>...</table>
    //   runs views/layout.php → <!doctype html>...the whole page...</html>
    //   and returns it as one text.
    // new Response(that text, 200) → object with status code 200, header and HTML.
    return new Response(view($view, $data), $status);
}

The Response object travels back the same way the call came: render() returns it to index(), index() returns it to dispatch(), dispatch() returns it to index.php, where it is stored in $response.

Step 9. $response->send() sends the response. In src/Http/Response.php:

public function send(): void
{
    http_response_code(200);                                  // first line of the response: 200 OK
    header('Content-Type: text/html; charset=UTF-8');         // header
    echo $this->body;                                         // HTML of the whole page
}

(In the real file the header is in a foreach loop, because there can be more of them; for our response there is one.)

Step 10. The browser displays the page. Apache adds the first line HTTP/1.1 200 OK to what PHP printed and sends it. The browser shows the menu, the heading Kategórie, the text Počet záznamov: 4 and the table:

id | name
1  | polievka
2  | hlavné jedlo
3  | dezert
4  | raňajky

Main entity: what the person wants and how the application does it

With the table recipes Ján Novák wants to do these things in the browser:

  • see the list of all recipes – clicks Recepty in the menu; address …/cv04/recipes
  • open one recipe – clicks its number in the list; address …/cv04/recipes/3
  • find recipes with some word in the title – types the word into the box above the list and clicks Hľadať; address …/cv04/recipes?q=tofu

All three requests are served by one controller, RecipeController. The list and the search are the same page, only with a filled or empty box, so the same method index() does both. The detail is done by the method show(). In index.php it is written like this:

$router->get('/recipes',      [RecipeController::class, 'index']);   // list; with ?q= also search
$router->get('/recipes/{id}', [RecipeController::class, 'show']);    // one recipe by number

The controller src/Controller/RecipeController.php, whole:

src/Controller/RecipeController.php
<?php
declare(strict_types=1);

namespace App\Controller;

use App\Http\Request;
use App\Http\Response;
use App\Model\RecipeModel;

final class RecipeController extends BaseController
{
    // Address /recipes and /recipes?q=tofu
    public function index(Request $request): Response
    {
        $model = new RecipeModel();
        $q     = $request->query('q');          // for /recipes → '';  for /recipes?q=tofu → 'tofu'
        $rows  = $q === ''                      // nothing searched?
            ? $model->getAll()                  // → all recipes
            : $model->search($q);               // → only recipes with 'tofu' in the title

        return $this->render('list', [
            'title' => $model->describe(),      // 'Recepty'
            'rows'  => $rows,
            'show'  => '/recipes',              // list.php makes a link in the id column from it: /recipes/3
            'q'     => $q,                      // list.php puts the searched text back into the form field
        ]);
    }

    // Address /recipes/3: the Router puts the number from the address into $id
    public function show(Request $request, int $id): Response
    {
        $model = new RecipeModel();
        $row   = $model->getById($id);          // for 3 → array with the record; for 999 → null
        if ($row === null) {
            return $this->notFound();           // “Not found” page, status code 404
        }

        return $this->render('show', [
            'title' => $row['title'],           // 'Tofu na sójovej omáčke s ryžou'
            'row'   => $row,
            'back'  => '/recipes',              // show.php makes the “Back to list” link from it
        ]);
    }
}

Ján Novák wants to open recipe number 3

He clicks the number 3 in the list. The browser sends a request for …/cv04/recipes/3. Steps 1–4 are the same as for the lookup; $request->path() is '/recipes/3'. The Router walks the list, at the sixth route:

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
    $class  = 'App\Controller\RecipeController';
    $action = 'show';
    $controller = new $class();
    return $controller->$action($request, ...$params);      // = $controller->show($request, 3)
}

show($request, 3) calls $model->getById(3); in RecipeModel a query with WHERE r.id = 3 is sent and one record comes back as an array: ['id' => 3, 'title' => '…', 'servings' => 4, …, 'difficulty_name' => 'ľahký']. render('show', …) runs views/show.php (prints the record as a list of column–value pairs) and views/layout.php, returns a Response with status code 200. Then as steps 8–10.

For …/cv04/recipes/999 everything is the same up to getById(999), which returns null. The controller returns $this->notFound():

protected function notFound(): Response
{
    return $this->render('404', ['title' => 'Nenájdené'], 404);   // views/404.php, status code 404
}

The browser shows the “Not found” page and the Network tab shows status code 404.

Ján Novák wants to find recipes with the word “tofu” in the title

He needs a box on the page to type the word into, and a button. That is the form in views/list.php; after the click it produces the address …/cv04/recipes?q=tofu. The form is at the beginning of views/list.php; the student writes it, the rest of the file is from cv03:

views/list.php
<?php /* Expects: $rows, optionally $show (detail address) and $q (searched text). */ ?>
<?php if (isset($q)): ?>                             <!-- the controller passed $q → the form is shown;
                                                          lookups do not pass $q → no form -->
    <form method="get" action="<?= url($show) ?>">   <!-- action = /student/jan.novak/it/cv04/recipes -->
        <input type="text" name="q" value="<?= e($q) ?>" placeholder="Hľadať v názve">
        <button type="submit">Hľadať</button>
        <a href="<?= url($show) ?>">Zrušiť</a>        <!-- list without search -->
    </form>
<?php endif; ?>
<?php if (!$rows): ?>
    <p>Žiadne záznamy.</p>
<?php else: ?>

The functions url() and e() are in src/helpers.php:

src/helpers.php
// Makes the full path for href from a relative address.
// url('/recipes') → '/student/jan.novak/it/cv04/recipes'
function url(string $path): string
{
    return BASE_URL . '/' . ltrim($path, '/');     // BASE_URL is from index.php
}

// Text for output into HTML: the characters < > & " are shown as characters, not as HTML.
// e('<b>tofu</b>') → '&lt;b&gt;tofu&lt;/b&gt;'  – the browser shows <b>tofu</b> as text
function e(?string $text): string
{
    return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8');
}

Ján Novák types tofu into the box and clicks Hľadať. The browser builds the address from action and the field (name="q", value tofu):

GET /student/jan.novak/it/cv04/recipes?q=tofu HTTP/1.1

It is the same request as if he had typed the address by hand. Apache puts into $_GET:

$_GET = ['q' => 'tofu'];

The application searches for recipes with the word “tofu”

The browser sent …/cv04/recipes?q=tofu. The application needs to select from the database the recipes whose title contains tofu; in SQL this is WHERE r.title LIKE '%tofu%'. How it gets there from the request to the query:

Request::fromGlobals() gives $path = '/recipes' (the part after ? is not part of the path) and $query = ['q' => 'tofu']. The Router finds the route /recipes and calls index($request). In index():

$q    = $request->query('q');     // 'tofu'
$rows = $model->search('tofu');   // in RecipeModel (term LIKE): 1 record, id 2

render('list', ['title' => 'Recepty', 'rows' => 1 record, 'show' => '/recipes', 'q' => 'tofu']) runs views/list.php: the form has tofu in the field (the line value="<?= e($q) ?>"), below it a table with one recipe. Then as steps 8–10.

Recipe list with search
…/cv04/recipes?q=tofu in the sample application: the field with the text tofu, below it a table with one recipe.

Debug page: when something does not work

What Ján Novák wants: he typed …/cv04/kategorie and got the “Not found” page although he is sure he has the categories list. He wants to see what the application did with his address, to find the mistake.

How the application helps him: he opens …/cv04/debug, then changes the end of the address to what did not work. The page prints what Apache put into $_SERVER and what Request computed from it. For …/cv04/kategorie he sees the value /kategorie in the row $request->path(); in index.php he has the route /categories. The typo is found. For …/cv04/debug?q=tofu he sees tofu in the last row, so the parameter from the address arrived.

Route in index.php:

$router->get('/debug', [HomeController::class, 'debug']);

Method in src/Controller/HomeController.php:

public function debug(Request $request): Response
{
    return $this->render('debug', ['title' => 'Debug', 'request' => $request]);  // the view gets the whole object
}

View views/debug.php:

views/debug.php
<?php /* Expects: $request (object App\Http\Request). */ ?>
<table>
    <!-- what Apache put into $_SERVER -->
    <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>
    <!-- what Request computed from it -->
    <tr><th>$request->method()</th>  <td><?= e($request->method()) ?></td></tr>
    <tr><th>$request->prefix()</th>  <td><?= e($request->prefix()) ?></td></tr>
    <tr><th>$request->path()</th>    <td><?= e($request->path()) ?></td></tr>
    <tr><th>$request->query('q')</th><td><?= e($request->query('q')) ?></td></tr>
</table>
<p>Zmeň koniec adresy, napríklad na <code>/debug?q=tofu</code>, a sleduj, čo sa v tabuľke zmení.</p>

What the page shows for …/cv04/debug?q=tofu:

$_SERVER['REQUEST_METHOD']   GET
$_SERVER['SCRIPT_NAME']      /student/jan.novak/it/cv04/index.php
$_SERVER['REQUEST_URI']      /student/jan.novak/it/cv04/debug?q=tofu
$request->method()           GET
$request->prefix()           /student/jan.novak/it/cv04
$request->path()             /debug                       ← without ?q=tofu
$request->query('q')         tofu

The whole HomeController.php, so that you see where home, check and debug are:

src/Controller/HomeController.php
<?php
declare(strict_types=1);

namespace App\Controller;

use App\Http\Request;
use App\Http\Response;

/** Pages without a table: home, check, debug. Your page /o-aplikacii goes here too (task 5.5). */
final class HomeController extends BaseController
{
    public function index(Request $request): Response
    {
        return $this->render('home', ['title' => 'Úvod']);                   // views/home.php
    }

    public function kontrola(Request $request): Response
    {
        return $this->render('kontrola', ['title' => 'Kontrola projektu']);  // views/kontrola.php
    }

    public function debug(Request $request): Response
    {
        return $this->render('debug', ['title' => 'Debug', 'request' => $request]);  // views/debug.php
    }
}

Fyzická podoba: priečinky, súbory, autoloaderPhysical form: folders, files, autoloader

Čo študent chce: vedieť, kde ktorý súbor leží, ktoré súbory dostane hotové, ktoré píše sám, a ako PHP nájde triedu App\Controller\CategoryController, keď o nej nikde nie je require.

Priečinky a súbory

Projekt cv04 Jána Nováka po dokončení cvičenia. Pri každom súbore je, odkiaľ je:

cv04/
├── .htaccess                         z cv03 bez zmeny
├── composer.json                     z cv03 bez zmeny
├── config.php                        z cv03 bez zmeny (heslo k databáze; nie je na GitHub)
├── config.example.php, .gitignore    z cv03 bez zmeny
├── index.php                         mvc.zip
├── src/
│   ├── Database.php                  z cv02 bez zmeny
│   ├── helpers.php                   z cv03 bez zmeny: e(), url(), view()
│   ├── Router.php                    mvc.zip
│   ├── Http/                         nový priečinok, mvc.zip
│   │   ├── Request.php
│   │   └── Response.php
│   ├── Controller/                   nový priečinok
│   │   ├── BaseController.php        mvc.zip
│   │   ├── HomeController.php        mvc.zip
│   │   ├── CategoryController.php    píše Ján Novák – jeden pre každý číselník
│   │   ├── DifficultyController.php  píše Ján Novák
│   │   └── RecipeController.php      píše Ján Novák – hlavná entita
│   └── Model/                        z cv02; do RecipeModel.php pridá search()
├── views/
│   ├── layout.php, home.php, 404.php, kontrola.php, show.php   z cv03 bez zmeny
│   ├── debug.php                     mvc.zip
│   └── list.php                      z cv03; na začiatok pridá formulár
├── sql/                              z cv02 bez zmeny
└── vendor/                           vytvorí composer install v Kubeflow (nižšie); nie je na GitHub

mvc.zip má sedem súborov: index.php, src/Router.php, src/Http/Request.php, src/Http/Response.php, src/Controller/BaseController.php, src/Controller/HomeController.php, views/debug.php. Študent píše controllery pre svoje tabuľky, metódu search() a formulár. Vzorová aplikácia je vo vzor-cv04.zip.

Autoloader: ako PHP nájde súbor s triedou

Čo študent chce: v index.php napíše new Router(), v Routeri new $class(), v controlleri new CategoryModel(), a nikde žiadny require na tieto súbory. Niekto ich musí nájsť.

Raz, v Kubeflow, pri založení projektu. V composer.json sú pre Composer dve informácie: triedy App\… sú v priečinku src/, a súbor src/helpers.php sa má načítať pri každej požiadavke hneď:

composer.json
"autoload": {
    "psr-4": { "App\\": "src/" },
    "files": [ "src/helpers.php" ]
}

Ján Novák otvorí v Kubeflow terminál (menu Terminal → New Terminal; dole sa objaví riadok s kurzorom), prejde do priečinka projektu a raz spustí Composer:

cd ~/web/it/cv04
composer install

Composer si tie dve informácie prečíta a vyrobí priečinok vendor/ so súborom vendor/autoload.php, v ktorom je kód, ktorý to zabezpečí. vendor/ vidí v Explorer pod cv04. Na sigma.tuke.sk ho dostane cez pravý klik na cv04 → Upload Folder. Viac s Composerom dnes nerobí.

Pri každej požiadavke, na sigma.tuke.sk. Keď Apache spustí index.php, riadok require __DIR__ . '/vendor/autoload.php'; načíta autoloader. Od tej chvíle v tejto požiadavke platí: keď kód použije triedu, ktorú PHP ešte nemá načítanú, autoloader z jej názvu zloží cestu a súbor načíta. Ján Novák nerobí nič; deje sa to samo pri každej návšteve stránky.

kód použije                              autoloader načíta
new Router()                        →    src/Router.php
Request::fromGlobals()              →    src/Http/Request.php
new $class()  (CategoryController)  →    src/Controller/CategoryController.php
new CategoryModel()                 →    src/Model/CategoryModel.php

Pravidlo skladania cesty: App\ nahradí src/, každé ďalšie \ je lomka priečinka, na koniec .php. Preto musí názov súboru presne sedieť s názvom triedy, aj veľkými písmenami, a priečinok s časťou názvu za App\. CategoryController.php v src/Controller/ s namespace App\Controller; autoloader nájde; ten istý súbor uložený do src/ nenájde a PHP skončí chybou Class "App\Controller\CategoryController" not found.

Nové priečinky src/Http/ a src/Controller/ nepotrebujú zmenu v composer.json: pravidlo App\ → src/ ich pokrýva.

Kde čo beží a kedy

  • Kubeflow je miesto, kde Ján Novák píše kód a spúšťa príkazy v termináli (composer install, git). Žiadna stránka tu nebeží.
  • sigma.tuke.sk je miesto, kde beží všetko, čo vidí v prehliadači: Apache číta .htaccess, spúšťa index.php, PHP načíta autoloader, vytvorí Request, Router, controller, model, model sa pripojí k databáze (tá beží na tom istom serveri, preto je v config.php host = localhost), view() vyrobí HTML, send() ho pošle. Toto celé prebehne pri každej jednej požiadavke znova, od začiatku; po odoslaní odpovede PHP všetko zahodí. Ďalšia požiadavka začína opäť od index.php.

Najčastejšie chyby a čo znamenajú

Čo vidíš Príčina Riešenie
Class "App\Http\Request" not found src/Http/ chýba na sigma.tuke.sk, alebo vendor/ je ešte z cv03 Upload Folder; composer install a Upload Folder
Class "App\Controller\CategoryController" not found názov súboru v src/Controller/ je iný než názov triedy, alebo namespace nie je App\Controller názov súboru = názov triedy + .php; skontroluj riadok namespace
Call to undefined method …Controller::index() v route je názov metódy, ktorú controller nemá porovnaj druhý prvok dvojice v get() s názvom metódy v controlleri
Return value must be of type App\Http\Response, string returned metóda controllera vracia view(…) return $this->render(…)
Return value must be of type App\Http\Response, none returned v metóde controllera chýba return return $this->render(…)
Warning: Cannot modify header information - headers already sent text vypísaný pred send(): echo v controlleri, alebo medzera pred <?php v súbore v src/ controller vracia Response; odstráň znaky pred <?php
Too few arguments to function …::show(), 1 passed … exactly 2 expected route detailu nemá {id} /hlavna-entita/{id}
Undefined variable $request vo view view číta $request, controller ho v render() neposlal 'request' => $request v poli pre render()
tvoja stránka 404 pre adresu, ktorú máš v get() preklep v adrese alebo v get() otvor /debug s tou istou koncovkou a porovnaj path() s adresou v get()
formulár odošle na sigma.tuke.sk/recipes v action je /recipes namiesto url($show) url()
hľadanie vráti vždy všetky záznamy v search() chýba % okolo hodnoty '%' . $q . '%'
hľadanie vráti vždy prázdny výsledok v WHERE je stĺpec, ktorý tvoja tabuľka nemá názov stĺpca s názvom z tvojej tabuľky

What the student wants: to know where each file lies, which files come ready, which they write themselves, and how PHP finds the class App\Controller\CategoryController when there is no require for it anywhere.

Folders and files

Ján Novák’s project cv04 after finishing the lab. Next to every file is where it comes from:

cv04/
├── .htaccess                         from cv03, unchanged
├── composer.json                     from cv03, unchanged
├── config.php                        from cv03, unchanged (database password; not on GitHub)
├── config.example.php, .gitignore    from cv03, unchanged
├── index.php                         mvc.zip
├── src/
│   ├── Database.php                  from cv02, unchanged
│   ├── helpers.php                   from cv03, unchanged: e(), url(), view()
│   ├── Router.php                    mvc.zip
│   ├── Http/                         new folder, mvc.zip
│   │   ├── Request.php
│   │   └── Response.php
│   ├── Controller/                   new folder
│   │   ├── BaseController.php        mvc.zip
│   │   ├── HomeController.php        mvc.zip
│   │   ├── CategoryController.php    written by Ján Novák – one for each lookup table
│   │   ├── DifficultyController.php  written by Ján Novák
│   │   └── RecipeController.php      written by Ján Novák – main entity
│   └── Model/                        from cv02; he adds search() to RecipeModel.php
├── views/
│   ├── layout.php, home.php, 404.php, kontrola.php, show.php   from cv03, unchanged
│   ├── debug.php                     mvc.zip
│   └── list.php                      from cv03; he adds the form at the beginning
├── sql/                              from cv02, unchanged
└── vendor/                           created by composer install in Kubeflow (below); not on GitHub

mvc.zip has seven files: index.php, src/Router.php, src/Http/Request.php, src/Http/Response.php, src/Controller/BaseController.php, src/Controller/HomeController.php, views/debug.php. The student writes the controllers for their tables, the method search() and the form. The sample application is in vzor-cv04.zip.

Autoloader: how PHP finds the file with a class

What the student wants: in index.php they write new Router(), in the Router new $class(), in a controller new CategoryModel(), and nowhere a require for these files. Somebody has to find them.

Once, in Kubeflow, when the project is set up. composer.json holds two pieces of information for Composer: the classes App\… are in the folder src/, and the file src/helpers.php is to be loaded right away on every request:

composer.json
"autoload": {
    "psr-4": { "App\\": "src/" },
    "files": [ "src/helpers.php" ]
}

Ján Novák opens a terminal in Kubeflow (menu Terminal → New Terminal; a line with a cursor appears at the bottom), goes to the project folder and runs Composer once:

cd ~/web/it/cv04
composer install

Composer reads the two pieces of information and produces the folder vendor/ with the file vendor/autoload.php, which contains the code that takes care of it. He sees vendor/ in the Explorer under cv04. He gets it to sigma.tuke.sk by right-clicking cv04 → Upload Folder. He does nothing more with Composer today.

On every request, on sigma.tuke.sk. When Apache runs index.php, the line require __DIR__ . '/vendor/autoload.php'; loads the autoloader. From that moment, within this request: when the code uses a class PHP has not loaded yet, the autoloader builds the path from its name and loads the file. Ján Novák does nothing; it happens by itself on every visit of a page.

the code uses                            the autoloader loads
new Router()                        →    src/Router.php
Request::fromGlobals()              →    src/Http/Request.php
new $class()  (CategoryController)  →    src/Controller/CategoryController.php
new CategoryModel()                 →    src/Model/CategoryModel.php

The rule for building the path: App\ is replaced by src/, every further \ is a folder slash, .php is appended. That is why the file name must match the class name exactly, including capital letters, and the folder must match the part of the name after App\. CategoryController.php in src/Controller/ with namespace App\Controller; is found by the autoloader; the same file saved into src/ is not, and PHP ends with the error Class "App\Controller\CategoryController" not found.

The new folders src/Http/ and src/Controller/ need no change in composer.json: the rule App\ → src/ covers them.

Where things run and when

  • Kubeflow is where Ján Novák writes code and runs commands in the terminal (composer install, git). No page runs here.
  • sigma.tuke.sk is where everything he sees in the browser runs: Apache reads .htaccess, runs index.php, PHP loads the autoloader, creates Request, the Router, the controller, the model, the model connects to the database (which runs on the same server, which is why host in config.php is localhost), view() builds the HTML, send() sends it. All of this runs again on every single request, from the start; after sending the response PHP throws everything away. The next request starts again from index.php.

Common errors and what they mean

What you see Cause Fix
Class "App\Http\Request" not found src/Http/ is missing on sigma.tuke.sk, or vendor/ is still from cv03 Upload Folder; composer install and Upload Folder
Class "App\Controller\CategoryController" not found the file name in src/Controller/ differs from the class name, or namespace is not App\Controller file name = class name + .php; check the namespace line
Call to undefined method …Controller::index() the route names a method the controller does not have compare the second element of the pair in get() with the method name in the controller
Return value must be of type App\Http\Response, string returned the controller method returns view(…) return $this->render(…)
Return value must be of type App\Http\Response, none returned return is missing in the controller method return $this->render(…)
Warning: Cannot modify header information - headers already sent text printed before send(): echo in a controller, or a space before <?php in a file in src/ the controller returns a Response; remove characters before <?php
Too few arguments to function …::show(), 1 passed … exactly 2 expected the detail route has no {id} /main-entity/{id}
Undefined variable $request in a view the view reads $request, the controller did not pass it in render() 'request' => $request in the array for render()
your 404 page for an address you have in get() typo in the address or in get() open /debug with the same ending and compare path() with the address in get()
the form submits to sigma.tuke.sk/recipes action has /recipes instead of url($show) url()
the search always returns all records % around the value is missing in search() '%' . $q . '%'
the search always returns an empty result WHERE uses a column your table does not have the name of your title column

Úlohy na cvičenieLab tasks

Úlohy dostaneš aj ako zadanie cv04 v Classroom 50, sú v súbore README.md v tvojom repository. Repository má na začiatku len README.md.

Link na zadanie cv04: prijať zadanie (platí pre skupiny B. Stehlíkovej; ostatné skupiny dostanú link od svojho cvičiaceho)

Úloha 5.1: Repository cv04 z cv03 a mvc.zip. Prijmi zadanie cv04 (link je vyššie) a repository naklonuj do ~/web/it/cv04 podľa návodu 04 Odovzdávanie, časti 2 a 3 (posledné slovo príkazu je cv04). Potom v termináli v Kubeflow:

cd ~/web/it
cp cv03/config.php cv03/config.example.php cv03/.gitignore cv03/.htaccess cv03/composer.json cv04/
cp -r cv03/sql cv03/src cv03/views cv04/
cd cv04
curl -O https://beata.stehlikova.website.tuke.sk/it/mvc.zip
unzip -o mvc.zip && rm mvc.zip
composer install

Čo sa stalo: z cv03 sú v cv04 všetky súbory okrem .git/, vendor/ a README.md. unzip -o prepísal index.php, src/Router.php a views/debug.php novou verziou a vytvoril src/Http/ a src/Controller/. composer install vytvoril vendor/. V Explorer vľavo klikni na šípku pri cv04: vidíš src/Http s dvoma súbormi a src/Controller s dvoma súbormi.

Pravý klik na priečinok cv04 → Upload Folder. Kontrola v prehliadači: https://sigma.tuke.sk/student/meno.priezvisko/it/cv04/ ukáže úvodnú stránku s menu, …/cv04/debug ukáže tabuľku so siedmimi riadkami, …/cv04/nic ukáže stránku „Nenájdené“. Commit a push: cv04: kostra MVC.

Úloha 5.2: Controller pre každý číselník. Pre každý svoj číselník, napríklad categories:

  1. V Explorer pravý klik na cv04/src/Controller → New File…, názov CategoryController.php. Obsah je v časti Pojmy, pojem Controller; zmeň názov triedy, názov modelu v use a v new.
  2. V index.php pridaj k riadkom use riadok use App\Controller\CategoryController; a medzi route riadok $router->get('/categories', [CategoryController::class, 'index']);.
  3. Vo views/layout.php pridaj do menu <a href="<?= url('/categories') ?>">Kategórie</a>.
  4. Ulož všetky tri súbory (Ctrl+S; uloženie ide na sigma.tuke.sk samo). Kontrola: …/cv04/categories ukáže tabuľku záznamov, odkaz v menu na ňu vedie.

Úloha 5.3: Controller hlavnej entity. Vytvor src/Controller/TvojaEntitaController.php s metódami index() a show() podľa RecipeController v časti „Ako to funguje“; zatiaľ bez vyhľadávania: v index() použi $model->getAll() a $q vynechaj. V index.php pridaj use a dve route: /tvoja-entita → index, /tvoja-entita/{id} → show. Do menu pridaj odkaz. Kontrola: zoznam sa zobrazí, klik na číslo v stĺpci id otvorí detail, …/tvoja-entita/999 ukáže stránku „Nenájdené“ a v karte Network (F12 → Network) stavový kód 404.

Úloha 5.4: Vyhľadávanie. Do svojho modelu hlavnej entity pridaj metódu search() podľa pojmu LIKE, so svojím stĺpcom názvu vo WHERE a so svojím JOIN. V index() controllera doplň riadky s $q a search() podľa RecipeController. Na začiatok views/list.php pridaj formulár z časti „Ako to funguje“. Kontrola: nad zoznamom je pole a tlačidlo; po zadaní slova, ktoré je v názve niektorého záznamu, ostane v tabuľke len ten; adresa v prehliadači má na konci ?q=slovo; po kliknutí na Zrušiť je zoznam celý.

Úloha 5.5: Stránka o aplikácii. Stránku /o-aplikacii z cv03 presuň do controllera: v src/Controller/HomeController.php pridaj metódu about(), ktorá vráti $this->render('about', ['title' => 'O aplikácii']); views/about.php máš z cv03. V index.php pridaj route /o-aplikacii → [HomeController::class, 'about']. Kontrola: adresa aj odkaz v menu fungujú.

Úloha 5.6: Odovzdanie. Commit a push podľa návodu 04 Odovzdávanie, časť 5. Na GitHub skontroluj, že je tam src/Http/ s dvoma súbormi, src/Controller/ s BaseController.php, HomeController.php a tvojimi controllermi, views/list.php s formulárom, tvoj model so search(). config.php a vendor/ tam nie sú.

Úloha 5.7: Kontrola na sigma.tuke.sk. Pravý klik na cv04 → Upload Folder. Preklikaj menu: úvod, každý číselník, hlavná entita, jeden detail, vyhľadávanie, kontrola, o aplikácii. Potom over, že …/cv04/nic ukáže stránku „Nenájdené“, …/cv04/src/Router.php vráti 404 a …/cv04/config.php vráti 403. Do README.md doplň tabuľku všetkých route: relatívna adresa, controller a metóda, čo zobrazí.

Ak si chceš pozrieť súbory na sigma.tuke.sk vo WinSCP, .htaccess a .gitignore sú skryté. Zapneš ich takto: v hornom menu WinSCP klikni na Options → Preferences; v okne vľavo klikni na Panels; vpravo v časti Common zaškrtni Show hidden files; OK. Rýchlejšie: Ctrl+Alt+H prepína zobrazenie skrytých súborov. V Explorer v Kubeflow sú tieto súbory vidieť vždy, len sivšie.

Hodnotenie: 1 bod. Aplikácia vo webovom priestore na sigma.tuke.sk má controller pre každú tabuľku, zoznam hlavnej entity má vyhľadávanie, neexistujúca adresa a neexistujúci záznam vrátia stavový kód 404. Commit a push najneskôr do nasledujúceho cvičenia.

You also get the tasks as the assignment cv04 in Classroom 50, in the file README.md in your repository. The repository starts with README.md only.

Link to the assignment cv04: accept the assignment (for B. Stehlíková’s groups; other groups get the link from their teacher)

Task 5.1: Repository cv04 from cv03 and mvc.zip. Accept the assignment cv04 (link above) and clone the repository into ~/web/it/cv04 following the guide 04 Submitting, parts 2 and 3 (the last word of the command is cv04). Then in the terminal in Kubeflow:

cd ~/web/it
cp cv03/config.php cv03/config.example.php cv03/.gitignore cv03/.htaccess cv03/composer.json cv04/
cp -r cv03/sql cv03/src cv03/views cv04/
cd cv04
curl -O https://beata.stehlikova.website.tuke.sk/it/mvc.zip
unzip -o mvc.zip && rm mvc.zip
composer install

What happened: all files from cv03 are in cv04 except .git/, vendor/ and README.md. unzip -o replaced index.php, src/Router.php and views/debug.php with the new version and created src/Http/ and src/Controller/. composer install created vendor/. In the Explorer on the left click the arrow at cv04: you see src/Http with two files and src/Controller with two files.

Right-click the folder cv04 → Upload Folder. Check in the browser: https://sigma.tuke.sk/student/meno.priezvisko/it/cv04/ shows the home page with the menu, …/cv04/debug shows a table with seven rows, …/cv04/nic shows the “Not found” page. Commit and push: cv04: kostra MVC.

Task 5.2: A controller for every lookup table. For every lookup table of yours, for example categories:

  1. In the Explorer right-click cv04/src/Controller → New File…, name CategoryController.php. The content is in the part Terms, term Controller; change the class name and the model name in use and in new.
  2. In index.php add the line use App\Controller\CategoryController; to the use lines and the line $router->get('/categories', [CategoryController::class, 'index']); among the routes.
  3. In views/layout.php add <a href="<?= url('/categories') ?>">Kategórie</a> to the menu.
  4. Save all three files (Ctrl+S; saving goes to sigma.tuke.sk by itself). Check: …/cv04/categories shows the table of records, the menu link leads to it.

Task 5.3: Main entity controller. Create src/Controller/YourEntityController.php with the methods index() and show() following RecipeController in the part “How it works”; without search for now: in index() use $model->getAll() and leave out $q. In index.php add use and two routes: /your-entity → index, /your-entity/{id} → show. Add a menu link. Check: the list is shown, a click on a number in the id column opens the detail, …/your-entity/999 shows the “Not found” page and the Network tab (F12 → Network) shows status code 404.

Task 5.4: Search. Add the method search() to your main entity model following the term LIKE, with your title column in WHERE and your JOIN. In the controller’s index() add the lines with $q and search() following RecipeController. Add the form from the part “How it works” to the beginning of views/list.php. Check: there is a field and a button above the list; after entering a word that is in the title of some record, only that one stays in the table; the address in the browser ends with ?q=word; after clicking Zrušiť the list is complete.

Task 5.5: About page. Move the page /o-aplikacii from cv03 into a controller: in src/Controller/HomeController.php add the method about() that returns $this->render('about', ['title' => 'O aplikácii']); you have views/about.php from cv03. In index.php add the route /o-aplikacii → [HomeController::class, 'about']. Check: the address and the menu link work.

Task 5.6: Submission. Commit and push following the guide 04 Submitting, part 5. On GitHub check that there is src/Http/ with two files, src/Controller/ with BaseController.php, HomeController.php and your controllers, views/list.php with the form, your model with search(). config.php and vendor/ are not there.

Task 5.7: Check on sigma.tuke.sk. Right-click cv04 → Upload Folder. Click through the menu: home, every lookup table, main entity, one detail, search, check, about. Then verify that …/cv04/nic shows the “Not found” page, …/cv04/src/Router.php returns 404 and …/cv04/config.php returns 403. In README.md add a table of all routes: relative address, controller and method, what it shows.

If you want to look at the files on sigma.tuke.sk in WinSCP, .htaccess and .gitignore are hidden. Turn them on like this: in the WinSCP top menu click Options → Preferences; in the window on the left click Panels; on the right in the Common part tick Show hidden files; OK. Faster: Ctrl+Alt+H toggles hidden files. In the Explorer in Kubeflow these files are always visible, only greyed.

Grading: 1 point. The application in your web space on sigma.tuke.sk has a controller for every table, the main entity list has search, a non-existent address and a non-existent record return status code 404. Commit and push by the next lab at the latest.

Obhajoba a live codingDefence and live coding

Pri obhajobe budú použité iba zverejnené otázky a úlohy. Druhý míľnik (7. týždeň) pokrýva týždne 5–7: dostaneš jednu položku z „Vysvetli“, jednu z „Uprav“ a jednu zo „Zdôvodni“ z tohto týždňa alebo z ďalších dvoch, 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 obhajoba2
cp -r cv06/. obhajoba2/
rm -rf obhajoba2/.git

Potom pravý klik na obhajoba2 → Upload Folder. Live coding sa robí v obhajoba2; uloženie v editore ide na sigma.tuke.sk samo; adresa je …/it/obhajoba2/. 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ť:

  1. Čo je MVC; ukáž vo svojom projekte priečinok pre každú z troch skupín a povedz, čo v ňom je.
  2. Čo urobí Apache s adresou …/cv04/categories a ktoré riadky .htaccess ho k tomu vedú.
  3. Čo je v $_SERVER['REQUEST_URI'] a $_SERVER['SCRIPT_NAME'] pre adresu svojej aplikácie; ukáž to na stránke /debug.
  4. Čo je Request, kde vzniká a čo má v sebe pre adresu …/tvoja-entita?q=abc.
  5. Čo robí Request::fromGlobals() riadok po riadku.
  6. Čo znamená :: a čo je TvojController::class; čo vypíše echo TvojController::class;.
  7. Čo je route a čo znamená riadok $router->get('/tvoja-tabulka', [TvojController::class, 'index']);.
  8. Čo robí Router::dispatch(): ako nájde route, ako vytvorí controller, ako zavolá metódu.
  9. Čo je controller a čo je metóda controllera; čo dostane a čo vráti.
  10. Prečo každý controller dedí od BaseController; čo má od neho.
  11. Čo robí render() krok za krokom; čo je $this v render().
  12. Čo robí funkcia view(): extract(), ob_start(), ob_get_clean().
  13. Čo je Response a čo má v sebe; čo urobí send() a ktoré funkcie PHP pri tom použije.
  14. Prečo je echo v celej aplikácii len na jednom mieste a kde.
  15. Kedy stránku 404 vráti Router a kedy notFound() v controlleri; ukáž obe adresy.
  16. Ako z formulára vznikne adresa s ?q=; kam sa hodnota dostane a ako ju číta controller.
  17. Čo robí LIKE '%abc%' a prečo je hodnota v execute() a nie priamo v SQL.
  18. Ako autoloader z názvu App\Controller\TvojController zloží cestu k súboru; čo sa stane, keď názov súboru nesedí.
  19. Čo sa deje v Kubeflow a čo na sigma.tuke.sk; kde beží composer install a kde beží index.php.
  20. Prečo sa pri každej požiadavke začína od index.php a nič si aplikácia nepamätá z predchádzajúcej.

Uprav (live coding)

Zmeny v kóde vidno v prehliadači po uložení. Nič z toho trvalo nemení dáta.

  1. Pridaj do HomeController metódu pocet() a route /pocet, ktorá zobrazí počet záznamov hlavnej entity (getCount()).
  2. Pridaj do controllera jedného číselníka metódu show() a route /ciselnik/{id}, ktorá zobrazí jeden záznam cez views/show.php.
  3. Zmeň show() hlavnej entity tak, aby pre neexistujúce id zobrazila zoznam namiesto stránky 404.
  4. Pridaj do vyhľadávania druhý parameter adresy (?q=abc&max=2), ktorý obmedzí počet zobrazených záznamov (array_slice v controlleri).
  5. Zmeň search() tak, aby hľadal aj v druhom stĺpci (OR).
  6. Pridaj do Response metódu withHeader(string $name, string $value): self a použi ju v debug() na hlavičku X-Debug: 1; ukáž ju v karte Network.
  7. Pridaj do stránky /debug riadok s počtom route v Routeri (nová metóda Router::count()).
  8. Zmeň notFound() tak, aby do stránky 404 poslal aj adresu, ktorá sa hľadala ($request->path()), a vypíš ju vo views/404.php.
  9. Vysvetli bez spúšťania, čo vráti dispatch() pre adresy /tvoja-entita/3/, /Tvoja-entita/3, /tvoja-entita/03, /tvoja-entita/3?x=1; potom to over v prehliadači.
  10. Presuň route jedného číselníka za riadok $response = $router->dispatch($request); a vysvetli, čo sa stane; potom vráť späť.

Zdôvodni (design decisions)

  1. Prečo je kód každej tabuľky vo vlastnom controlleri a nie v index.php.
  2. Prečo controller vracia Response a nevypisuje HTML cez echo.
  3. Prečo sú hodnoty z $_SERVER a $_GET zabalené v objekte Request a nečíta ich každý controller sám.
  4. Prečo render() a notFound() sú v BaseController a nie v každom controlleri.
  5. Prečo sa metódy volajú index a show a nie napríklad zoznam a detail.
  6. Prečo hľadaný text ide do SQL cez parameter :q a nie spojením reťazcov.

Definition of Done

Týždeň je hotový, keď:

  • každá tvoja tabuľka má controller v src/Controller/ a route v index.php; v index.php nie je žiadna anonymná funkcia,
  • zoznam hlavnej entity má pole na hľadanie a …/tvoja-entita?q=slovo zobrazí len záznamy so slovom v názve,
  • …/cv04/tvoja-entita/999 a …/cv04/nic zobrazia stránku „Nenájdené“ a v karte Network je stavový kód 404,
  • …/cv04/debug zobrazí tabuľku so siedmimi riadkami,
  • …/cv04/src/Router.php vráti 404 a …/cv04/config.php vráti 403,
  • README.md má tabuľku route s controllerom a metódou,
  • commit a push sú na GitHub, vendor/ ani config.php v repository nie sú.

Only the published questions and tasks are used at the defence. The second milestone (week 7) covers weeks 5–7: you get one item from “Explain”, one from “Modify” and one from “Justify” from this week or the next two, 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 obhajoba2
cp -r cv06/. obhajoba2/
rm -rf obhajoba2/.git

Then right-click obhajoba2 → Upload Folder. Live coding is done in obhajoba2; saving in the editor goes to sigma.tuke.sk by itself; the address is …/it/obhajoba2/. The repository and GitHub do not change. The “Modify” tasks are also extension tasks for the fast ones: whoever tries them in advance has an easier defence.

Explain (code walkthrough)

Over your own project you can say:

  1. What MVC is; show in your project the folder for each of the three groups and say what is in it.
  2. What Apache does with the address …/cv04/categories and which lines of .htaccess lead it there.
  3. What is in $_SERVER['REQUEST_URI'] and $_SERVER['SCRIPT_NAME'] for an address of your application; show it on the /debug page.
  4. What Request is, where it is created and what it holds for the address …/your-entity?q=abc.
  5. What Request::fromGlobals() does line by line.
  6. What :: means and what YourController::class is; what echo YourController::class; prints.
  7. What a route is and what the line $router->get('/your-table', [YourController::class, 'index']); means.
  8. What Router::dispatch() does: how it finds the route, how it creates the controller, how it calls the method.
  9. What a controller is and what a controller method is; what it receives and what it returns.
  10. Why every controller extends BaseController; what it gets from it.
  11. What render() does step by step; what $this is in render().
  12. What the function view() does: extract(), ob_start(), ob_get_clean().
  13. What Response is and what it holds; what send() does and which PHP functions it uses.
  14. Why echo is in one place only in the whole application, and where.
  15. When the Router returns the 404 page and when notFound() in the controller does; show both addresses.
  16. How the address with ?q= is made from the form; where the value goes and how the controller reads it.
  17. What LIKE '%abc%' does and why the value is in execute() and not directly in the SQL.
  18. How the autoloader builds the file path from the name App\Controller\YourController; what happens when the file name does not match.
  19. What happens in Kubeflow and what on sigma.tuke.sk; where composer install runs and where index.php runs.
  20. Why every request starts from index.php and the application remembers nothing from the previous one.

Modify (live coding)

Code changes are visible in the browser after saving. None of this changes data permanently.

  1. Add the method pocet() to HomeController and the route /pocet, which shows the number of records of the main entity (getCount()).
  2. Add the method show() and the route /lookup/{id} to one lookup controller, showing one record through views/show.php.
  3. Change show() of the main entity so that for a non-existent id it shows the list instead of the 404 page.
  4. Add a second address parameter to the search (?q=abc&max=2) that limits the number of shown records (array_slice in the controller).
  5. Change search() so that it also searches in a second column (OR).
  6. Add the method withHeader(string $name, string $value): self to Response and use it in debug() for the header X-Debug: 1; show it in the Network tab.
  7. Add a row with the number of routes in the Router to the /debug page (new method Router::count()).
  8. Change notFound() so that it also passes the searched address ($request->path()) to the 404 page, and print it in views/404.php.
  9. Explain without running what dispatch() returns for the addresses /your-entity/3/, /Your-entity/3, /your-entity/03, /your-entity/3?x=1; then verify in the browser.
  10. Move the route of one lookup table after the line $response = $router->dispatch($request); and explain what happens; then move it back.

Justify (design decisions)

  1. Why the code of every table is in its own controller and not in index.php.
  2. Why the controller returns a Response and does not print the HTML with echo.
  3. Why the values from $_SERVER and $_GET are wrapped in a Request object instead of every controller reading them itself.
  4. Why render() and notFound() are in BaseController and not in every controller.
  5. Why the methods are called index and show and not, say, list and detail.
  6. Why the searched text goes into the SQL through the parameter :q and not by joining strings.

Definition of Done

The week is done when:

  • every table of yours has a controller in src/Controller/ and a route in index.php; there is no anonymous function in index.php,
  • the main entity list has a search field and …/your-entity?q=word shows only records with the word in the title,
  • …/cv04/your-entity/999 and …/cv04/nic show the “Not found” page and the Network tab shows status code 404,
  • …/cv04/debug shows a table with seven rows,
  • …/cv04/src/Router.php returns 404 and …/cv04/config.php returns 403,
  • README.md has a route table with controller and method,
  • commit and push are on GitHub, neither vendor/ nor config.php is in the repository.