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

Kostra projektu a modelyProject skeleton and models

TeóriaTheory UkážkyExamples Úlohy na cvičenieLab tasks Obhajoba a live codingDefence and live coding

Dnes z dátového modelu vzniknú skutočné tabuľky v databáze a prvý kód projektu. Dostaneš hotovú kostru: Composer, jedno pripojenie k databáze, rodičovskú triedu pre číselníky a vzor pre hlavnú entitu. Ty doplníš SQL pre svoje tabuľky, testovacie dáta a modely pre svoju tému. Na konci cvičenia máš vo svojom webovom priestore na sigma.tuke.sk stránku, ktorá vypíše záznamy z každej tvojej tabuľky. Pojmy sú v tabuľke pojmov.

Today the data model turns into real tables in the database and the first code of the project. You get a ready-made skeleton: Composer, one database connection, a parent class for lookup tables and an example for the main entity. You add the SQL for your tables, test data and the models for your topic. By the end of the lab you have a page in your web space on sigma.tuke.sk that lists the records of every table. The terms are in the table of terms.

TeóriaTheory

Čo dnes dostaneš a čo s tým urobíš

Dostaneš kostru: balík súborov kostra.zip z webu predmetu (stiahnutie kliknutím, alebo príkazom curl v úlohe 3.2), rovnaký pre každého. Kostra nič nevie o tvojej téme. Ty do nej pridáš SQL pre svoje tabuľky, testovacie dáta a triedy pre svoje tabuľky.

Po rozbalení kostra.zip do priečinka cv02 v Kubeflow máš tieto súbory. Každý je vysvetlený v uvedenej časti:

cv02/
├── composer.json           zoznam pre program Composer: kde sú naše triedy          (časť 2)
├── .gitignore              zoznam, čo Git nedáva na GitHub                           (časť 2, 5)
├── .htaccess               nastavenie servera Apache pre tento priečinok             (časť 8)
├── config.example.php      vzor prihlasovacích údajov k databáze, bez hesla         (časť 5)
├── index.php               kontrolná stránka: vypíše tabuľky a dáta                 (Ukážka 5)
├── sql/
│   ├── schema.sql          prázdny; sem dáš CREATE TABLE pre svoje tabuľky          (časť 6)
│   └── seed.sql            prázdny; sem dáš testovacie dáta                         (časť 6)
└── src/                    naše triedy
    ├── Database.php        pripojenie k databáze                                    (časť 5)
    └── Model/
        ├── ModelInterface.php   zoznam metód, ktoré musí mať každý model            (časť 7)
        ├── BaseModel.php        rodič číselníkov, hotové metódy                     (časť 7)
        ├── LookupModel.php      vzor číselníka – skopíruješ a premenuješ            (časť 7)
        └── MainModel.php        vzor hlavnej entity – skopíruješ a premenuješ       (časť 7)
Priečinok projektu vo WinSCP
Ten istý priečinok vo webovom priestore na sigma.tuke.sk, pohľad cez WinSCP. Súbory s bodkou na začiatku (.htaccess, .gitignore) WinSCP zobrazí len so zapnutým zobrazovaním skrytých súborov.

Model je trieda, ktorá pracuje s jednou tabuľkou v databáze. Pre každú svoju tabuľku (okrem prepojok) budeš mať jeden súbor s jednou triedou. Vzory na to sú LookupModel.php a MainModel.php.

Až u teba vzniknú config.php (časť 5) a priečinok vendor/ (časť 2).

Postup cvičenia:

  1. Rozbalíš kostra.zip do ~/web/it/cv02 v Kubeflow.
  2. V termináli v cv02 spustíš composer install. Vznikne priečinok vendor/ (časť 2).
  3. Skopíruješ config.example.php na config.php a doplníš prihlasovacie údaje k databáze (časť 5).
  4. Pravým tlačidlom na cv02 → Upload Folder. Celý priečinok sa skopíruje na sigma.tuke.sk.
  5. Necháš si od AI vyrobiť sql/schema.sql a sql/seed.sql zo svojho README a spustíš ich v Adminer (časť 6).
  6. Necháš si od AI vyrobiť modely pre svoje tabuľky podľa vzorov v kostre a pridáš ich do index.php (časť 7).
  7. Commit a push.

Kde sú súbory:

Miesto Čo tam je Ako sa tam dostane
Kubeflow, ~/web/it/cv02 všetko: kostra, vendor/, config.php, tvoje súbory tu píšeš
sigma.tuke.sk, public_html/it/cv02 to isté; tu aplikácia beží súbor uložený v editore sa skopíruje sám; vendor/ a rozbalený ZIP cez Upload Folder
GitHub, repository cv02 kostra a tvoje súbory, bez vendor/ a config.php git add, commit, push
databáza na sigma.tuke.sk tvoje tabuľky a dáta schema.sql a seed.sql spustené v Adminer

Composer, composer.json, vendor

Composer je program v Kubeflow, ktorý sa spúšťa v termináli. Riadi sa súborom composer.json v priečinku projektu. Dnes ho potrebuješ na jedno: aby PHP samo našlo triedy v src/ (časť 4).

composer.json je textový súbor vo formáte JSON (zložené zátvorky, dvojbodky, úvodzovky). V kostre má tieto časti:

  • name, description – meno a popis projektu; informácia.
  • require – zoznam cudzích knižníc, ktoré projekt potrebuje. Je tam len "php": ">=8.1" (PHP aspoň 8.1), žiadna knižnica.
  • autoload → psr-4 → "App\\": "src/" – pravidlo, kde sú naše triedy (časť 4).
  • config → platform → "php": "8.1.2" – Composer sa správa, ako keby PHP bolo 8.1.2. Kubeflow má PHP 8.3, sigma.tuke.sk má 8.1; riadok zabráni stiahnutiu niečoho, čo by na sigma.tuke.sk nebežalo.

composer install napíšeš v termináli v Kubeflow v priečinku ~/web/it/cv02 (priečinok vidíš pred kurzorom; ak nie, cd ~/web/it/cv02). Composer prečíta composer.json a vytvorí v cv02 priečinok vendor/. V ňom je súbor vendor/autoload.php, ktorý index.php načíta ako prvý (časť 4), a pomocné súbory Composeru. Spúšťaš ho po každom clone a po každej zmene composer.json.

Kam vendor/ patrí a ako ho tam dostaneš:

  • Kubeflow – vznikne tu príkazom composer install. Nič viac netreba.
  • sigma.tuke.sk – aplikácia ho tu potrebuje, lebo index.php načíta vendor/autoload.php. Priečinok skopíruješ ručne: v Explorer klikni pravým tlačidlom na cv02 → Upload Folder. (Súbory uložené v editore sa kopírujú samy; vendor/ vytvoril Composer v termináli, preto o ňom editor nevie.) Rovnako po rozbalení ZIP-u.
  • GitHub – ostáva mimo. V .gitignore je riadok vendor/, takže git add ho preskočí. Kto stiahne repository, spustí composer install a má ho.

composer.lock vznikne pri composer install vedľa composer.json: zoznam presných verzií. Ide na GitHub.

Viac: getcomposer.org: Basic usage

Namespace: adresa triedy

Otvor src/Database.php. Za <?php a declare(strict_types=1); je riadok:

namespace App;

Namespace je adresa triedy. Plné meno triedy je adresa + spätná lomka + meno: App\Database. V src/Model/BaseModel.php je namespace App\Model;, plné meno App\Model\BaseModel.

Načo: v kostre máš triedu Database. Keď niekedy pridáš cudzí kód, ktorý má tiež triedu Database, PHP skončí chybou „Cannot declare class Database, because the name is already in use”. S adresou sú to dve mená: App\Database a Cudzia\Database.

Použitie triedy z inej adresy: na začiatok súboru napíšeš use s plným menom, ďalej používaš krátke:

use App\Database;

$pdo = Database::getInstance();

Tak to je v src/Model/BaseModel.php (čo metóda getInstance() robí, je v časti 5). Triedy z PHP (napríklad PDO) nemajú adresu; v súbore s namespace sa preto píše use PDO;, inak by PHP hľadalo App\PDO.

PSR-4: ako PHP nájde súbor s triedou

PHP potrebuje k plnému menu triedy súbor. Pravidlo je v composer.json:

"autoload": { "psr-4": { "App\\": "src/" } }

Adresa začínajúca App\ je v priečinku src/; zvyšok adresy je cesta; meno triedy je názov súboru s .php:

Plné meno triedy Súbor
App\Database src/Database.php
App\Model\ModelInterface src/Model/ModelInterface.php
App\Model\BaseModel src/Model/BaseModel.php
App\Model\LookupModel src/Model/LookupModel.php
App\Model\MainModel src/Model/MainModel.php

Z tohto pravidla Composer vyrobí vendor/autoload.php. V index.php je jediný require v celej aplikácii:

require __DIR__ . '/vendor/autoload.php';

Od tohto riadku PHP pri každom použití triedy, ktorú ešte nemá, zloží z adresy cestu a súbor načíta samo. Žiadny require_once sa inde nepíše.

Pre triedy, ktoré napíšeš v úlohe 3.4, platí: jeden súbor = jedna trieda; názov súboru sa zhoduje s menom triedy vrátane veľkých písmen (CategoryModel.php, trieda CategoryModel). Inak PHP súbor nenájde.

Viac: PHP-FIG: PSR-4

config.php a Database.php: prihlasovacie údaje a pripojenie

config.php je súbor v priečinku projektu s prihlasovacími údajmi k databáze. Vytvoríš ho v termináli v cv02:

cp config.example.php config.php

Otvoríš config.php v editore a doplníš svoje údaje:

config.php
<?php
return [
    'host'   => 'localhost',   // databáza beží na tom istom serveri ako PHP
    'dbname' => 'teacher',     // názov databázy = tvoj login do Adminer
    'user'   => 'teacher',     // login do databázy = ten istý
    'pass'   => 'teacher_psw', // heslo z cvičenia
    'debug'  => true,          // true: chyby PHP sa zobrazia v prehliadači
];
Prihlasovacie okno Adminer
Tie isté údaje zadávaš pri prihlásení do Adminer: Systém MySQL/MariaDB, Server localhost, Používateľ a Databáza = tvoj login, heslo z cvičenia.

Súbor vracia pole. Kto údaje potrebuje, napíše $c = require 'config.php'; a má ich v $c['host'], $c['user'] atď.

Kam config.php patrí: v Kubeflow ho vytvoríš; na sigma.tuke.sk sa dostane uložením v editore; na GitHub ostáva mimo, lebo je v .gitignore (v repository je len config.example.php bez hesla).

src/Database.php vytvára pripojenie k databáze. Použitie z ktorejkoľvek triedy:

$pdo = Database::getInstance();

getInstance() pri prvom zavolaní prečíta config.php, zloží z neho DSN (vysvetlené nižšie) a vytvorí objekt PDO. Pri každom ďalšom zavolaní vráti ten istý objekt. Celá aplikácia má jedno pripojenie. Konštruktor je private, takže new Database() nie je možné; jediná cesta je getInstance(). Tento tvar triedy sa volá singleton.

DSN je reťazec, ktorým sa PDO hovorí, kam sa pripojiť: mysql:host=localhost;dbname=teacher;charset=utf8mb4. Skladá sa z hodnôt v config.php. Používateľ a heslo sa dávajú PDO ako ďalšie dva parametre.

Tabuľky: schema.sql a seed.sql

sql/schema.sql je textový súbor s príkazmi CREATE TABLE pre všetky tabuľky tvojho projektu. sql/seed.sql je súbor s príkazmi INSERT s testovacími dátami. Oba sú v kostre prázdne. Vyrobíš ich cez prompt (Ukážka 7) zo svojho README a spustíš v Adminer: vľavo SQL command, vložiť obsah súboru, Execute. Najprv schema.sql, potom seed.sql.

Poradie v schema.sql: tabuľka s cudzím kľúčom sa dá vytvoriť až vtedy, keď existuje tabuľka, na ktorú odkazuje. Preto: najprv číselníky, potom hlavná entita, nakoniec prepojky. Na začiatku súboru je DROP TABLE IF EXISTS pre každú tabuľku v opačnom poradí (prepojky, hlavná entita, číselníky). Súbor sa tak dá spustiť opakovane: keď si databázu pokazíš, spustíš oba súbory znova.

Zápis tabuľky:

CREATE TABLE difficulties (
    id   INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  • id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY – primárny kľúč, nezáporné celé číslo, databáza ho prideľuje sama.
  • ENGINE=InnoDB – typ tabuľky, ktorý kontroluje cudzie kľúče.
  • CHARSET=utf8mb4 – kódovanie pre slovenčinu.

Cudzí kľúč:

FOREIGN KEY (difficulty_id) REFERENCES difficulties(id) ON DELETE RESTRICT

Pravidlo ON DELETE je to, ktoré si zdôvodnil v README. Oba súbory sú v repository: kto projekt otvorí, vytvorí si rovnakú databázu.

Viac: W3Schools: SQL FOREIGN KEY

JOIN: dve tabuľky v jednom dotaze

V tabuľke recipes je stĺpec difficulty_id s číslom. Na stránke chceš text „stredný”, ktorý je v tabuľke difficulties. JOIN pripojí ku každému riadku receptu riadok obtiažnosti, ktorý k nemu patrí:

SELECT r.title, r.prep_time, d.name AS difficulty_name
FROM recipes r
JOIN difficulties d ON d.id = r.difficulty_id
ORDER BY r.id DESC;
  • FROM recipes r – začíname od receptov; r je skratka (alias) tabuľky.
  • JOIN difficulties d ON d.id = r.difficulty_id – ku každému receptu pripoj obtiažnosť, ktorej id sa rovná difficulty_id receptu. Za ON je vždy „primárny kľúč jednej tabuľky = cudzí kľúč druhej”.
  • d.name AS difficulty_name – stĺpec name z obtiažnosti pod iným menom, aby sa v PHP neplietol s iným name. V $row['difficulty_name'] je potom text.

Čo vráti na testovacích dátach vzoru (4 recepty, najnovší prvý):

title prep_time difficulty_name
Kari z červenej šošovice 45 náročný
Ovsená kaša s banánom a kakaom 10 ľahký
Tofu na sójovej omáčke s ryžou 25 stredný
Šošovicová polievka s kokosovým mliekom 35 ľahký

Bez JOIN by v poslednom stĺpci bolo len číslo difficulty_id (3, 1, 2, 1). Dotaz si môžeš spustiť v Adminer: SQL command, vložiť, Execute.

JOIN vráti len riadky, ktoré majú pár na druhej strane. LEFT JOIN vráti všetky riadky ľavej tabuľky aj bez páru, s NULL v stĺpcoch pravej.

Viac: W3Schools: SQL JOIN

Modely: triedy pre tabuľky

Pojmy z OOP, ktoré sú v kostre použité:

Pojem V kóde Čo to je
trieda class LookupModel { } predpis: aké vlastnosti a metódy bude mať objekt
objekt $m = new LookupModel(); konkrétna vec vytvorená podľa predpisu
vlastnosť protected string $table; premenná vnútri objektu
metóda public function getAll(): array funkcia objektu; : array je typ návratovej hodnoty
$this $this->pdo tento objekt, vnútri jeho metód
konštruktor public function __construct() metóda, ktorá sa spustí pri new
public / protected / private prístup: ktokoľvek / trieda a jej potomkovia / len trieda
dedenie class LookupModel extends BaseModel potomok má všetko public a protected z rodiča
abstraktná trieda abstract class BaseModel trieda len na dedenie; new BaseModel() nie je možné; abstraktná metóda nemá telo, potomok ju musí napísať
interface interface ModelInterface, implements zoznam metód bez kódu; trieda s implements ich musí všetky napísať
statická vlastnosť private static ?PDO $instance patrí triede, nie objektu
?array, ?PDO hodnota daného typu alebo null

Súbory v src/Model/:

ModelInterface.php – zoznam metód, ktoré má každý model: getAll(), getById(), getCount(), delete(), describe(). Bez kódu. index.php vďaka tomu zavolá describe() a getAll() na každom modeli rovnako.

BaseModel.php – abstraktná trieda, rodič číselníkov. Má hotové getAll(), getById(), getCount(), delete() a konštruktor, ktorý si vypýta pripojenie cez Database::getInstance(). Vlastnosť $table je protected bez hodnoty: doplní ju potomok. Metóda describe() je abstraktná: napíše ju potomok.

LookupModel.php – vzor číselníka. Celý vlastný kód má päť riadkov: extends BaseModel, $table = 'lookup_table' a describe(). Pre každý svoj číselník tento súbor skopíruješ a premenuješ: tabuľka categories → súbor CategoryModel.php, trieda CategoryModel, $table = 'categories'. Názov triedy: anglicky, jednotné číslo, prípona Model.

MainModel.php – vzor hlavnej entity. Nededí z BaseModel: jej getAll() a getById() majú JOIN na číselník, aby vrátili aj text namiesto čísla. Implementuje ModelInterface sama, má vlastný konštruktor a vlastné getCount(), delete(), describe(). Skopíruješ a premenuješ rovnako; v SQL nahradíš main_table, lookup_table, lookup_id svojimi názvami.

Vzorové LookupModel.php a MainModel.php po vytvorení vlastných tried zmažeš.

Kód vzorov z kostry, tak ako ich máš v src/Model/ (ModelInterface.php a BaseModel.php sú v Ukážke 3):

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

namespace App\Model;

/**
 * VZOR číselníka. Skopíruj tento súbor pre každý svoj číselník a premenuj:
 *   tabuľka categories  ->  súbor CategoryModel.php, trieda CategoryModel, $table = 'categories'
 * Názov triedy je v angličtine, jednotné číslo, končí na Model.
 * Všetko ostatné (getAll, getById, getCount, delete) dedí z BaseModel.
 */
class LookupModel extends BaseModel
{
    protected string $table = 'lookup_table'; // <- názov tvojej tabuľky

    public function describe(): string
    {
        return "Číselník {$this->table}";
    }
}
src/Model/MainModel.php
<?php
declare(strict_types=1);

namespace App\Model;

use App\Database;
use PDO;

/**
 * VZOR hlavnej entity. Skopíruj a premenuj podľa svojej tabuľky:
 *   tabuľka loans  ->  súbor LoanModel.php, trieda LoanModel
 * Hlavná entita nededí z BaseModel: jej dotazy sú iné (JOIN na číselník),
 * preto implementuje ModelInterface samostatne.
 *
 * V SQL dotazoch nahraď:
 *   main_table    názov hlavnej entity (napr. loans)
 *   lookup_table  názov číselníka pripojeného vzťahom 1:N (napr. statuses)
 *   lookup_id     cudzí kľúč na ten číselník (napr. status_id)
 */
class MainModel implements ModelInterface
{
    private PDO $pdo;

    public function __construct()
    {
        $this->pdo = Database::getInstance();
    }

    /** Všetky záznamy aj s názvom z číselníka (JOIN), najnovšie prvé. */
    public function getAll(): array
    {
        $sql = "SELECT m.*, l.name AS lookup_name
                FROM main_table m
                JOIN lookup_table l ON l.id = m.lookup_id
                ORDER BY m.id DESC";
        return $this->pdo->query($sql)->fetchAll();
    }

    public function getById(int $id): ?array
    {
        $sql = "SELECT m.*, l.name AS lookup_name
                FROM main_table m
                JOIN lookup_table l ON l.id = m.lookup_id
                WHERE m.id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch();
        return $row === false ? null : $row;
    }

    public function getCount(): int
    {
        return (int) $this->pdo->query("SELECT COUNT(*) FROM main_table")->fetchColumn();
    }

    public function delete(int $id): bool
    {
        $stmt = $this->pdo->prepare("DELETE FROM main_table WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->rowCount() > 0;
    }

    public function describe(): string
    {
        return 'Hlavná entita main_table';
    }
}

Prepared statement (z OOP): SQL s placeholderom :id ide do databázy osobitne, hodnota osobitne v execute([':id' => $id]). Databáza hodnotu spracuje ako dáta, nie ako SQL. Dotazy bez vstupu od používateľa (SELECT * FROM … ORDER BY id) idú cez query(). Názov tabuľky v {$this->table} nastavuje trieda, nie používateľ, preto môže byť v reťazci.

.htaccess: nastavenie servera pre priečinok

Apache je program na sigma.tuke.sk, ktorý prijíma požiadavky z prehliadača, nájde súbor v public_html a pošle ho späť; súbor .php predtým spustí. .htaccess je textový súbor s nastavením Apache pre priečinok, v ktorom leží, a pre jeho podpriečinky. Apache ho číta pri každej požiadavke; zmena platí ihneď. Chyba v ňom (preklep v príkaze) spôsobí chybu 500 na všetko v priečinku.

Meno začína bodkou: Linux ho považuje za skrytý súbor. WinSCP a Explorer vo VS Code ho zobrazia; Prieskumník vo Windows môže skryť.

.htaccess v kostre:

RedirectMatch 404 /(src|vendor|sql|\.git)(/|$)

Požiadavka na adresu s /src/, /vendor/, /sql/ alebo /.git/ dostane odpoveď 404. V týchto priečinkoch je kód a SQL, nie stránky.

<Files "config.php">
    Require all denied
</Files>

Požiadavka z prehliadača na config.php dostane odpoveď 403. PHP ho načítava normálne.

IndexIgnore *

Priečinok bez index.php nevypíše zoznam svojich súborov.

Overenie: v úlohe 3.7 otvoríš …/cv02/src/ a …/cv02/config.php; obe musia skončiť chybou 404 alebo 403.

Viac: Apache: .htaccess

Ako to funguje: kontrolná stránka od adresy po tabuľku

Čo Ján Novák chce: vidieť, či má v databáze tabuľky a či jeho modely čítajú dáta. Napíše https://sigma.tuke.sk/student/jan.novak/it/cv02/ a stlačí Enter.

Krok 1. Prehliadač pošle požiadavku GET /student/jan.novak/it/cv02/ serveru sigma.tuke.sk.

Krok 2. Apache na sigma.tuke.sk nájde súbor. Cesta ukazuje na priečinok public_html/it/cv02/; v priečinku je index.php, Apache ho spustí. (Riadky .htaccess z kostry tu nič neprepisujú; v cv02 má aplikácia jedinú stránku.)

Krok 3. Beží index.php. Celý súbor kostry; komentáre hovoria, čo sa deje:

index.php
<?php
declare(strict_types=1);

// Jediný require v celej aplikácii: Composer odteraz nájde každú triedu sám (PSR-4).
require __DIR__ . '/vendor/autoload.php';

$config = require __DIR__ . '/config.php';
if ($config['debug']) {
    ini_set('display_errors', '1');   // sigma.tuke.sk má chyby vypnuté, počas vývoja ich chceme vidieť
    error_reporting(E_ALL);
}

use App\Database;

$pdo = Database::getInstance();

// 1. Tabuľky, ktoré sú v databáze (po spustení schema.sql).
$tables = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);

// 2. Tvoje modely – po vytvorení tried doplň do zoznamu jeden riadok pre každú:
$models = [
    // new \App\Model\CategoryModel(),
    // new \App\Model\LoanModel(),
];
?>
<!doctype html>
<html lang="sk">
<head>
    <meta charset="utf-8">
    <title>Kontrola projektu</title>
    <style>
        body { font-family: system-ui, sans-serif; max-width: 60rem; margin: 2rem auto; padding: 0 1rem; }
        table { border-collapse: collapse; margin-bottom: 2rem; }
        th, td { border: 1px solid #999; padding: .3rem .6rem; text-align: left; }
        th { background: #eee; }
    </style>
</head>
<body>
<h1>Kontrola projektu</h1>

<h2>Tabuľky v databáze (<?= count($tables) ?>)</h2>
<ul>
    <?php foreach ($tables as $t): ?>
        <li><?= htmlspecialchars($t) ?></li>
    <?php endforeach; ?>
</ul>

<h2>Modely (<?= count($models) ?>)</h2>
<?php foreach ($models as $model): ?>
    <h3><?= htmlspecialchars($model->describe()) ?> – <?= $model->getCount() ?> záznamov</h3>
    <?php $rows = array_slice($model->getAll(), 0, 5); ?>
    <?php if ($rows): ?>
        <table>
            <tr><?php foreach (array_keys($rows[0]) as $col): ?><th><?= htmlspecialchars($col) ?></th><?php endforeach; ?></tr>
            <?php foreach ($rows as $row): ?>
                <tr><?php foreach ($row as $v): ?><td><?= htmlspecialchars((string) $v) ?></td><?php endforeach; ?></tr>
            <?php endforeach; ?>
        </table>
    <?php else: ?>
        <p>Tabuľka je prázdna – spusti seed.sql.</p>
    <?php endif; ?>
<?php endforeach; ?>
</body>
</html>

Riadok 5 načíta vendor/autoload.php od Composeru: od tejto chvíle PHP nájde každú triedu App\… v src/ samo. Riadky 7–11 načítajú config.php a zapnú výpis chýb. Riadok 15 zavolá Database::getInstance(): pri prvom zavolaní prečíta config.php, zloží DSN a vytvorí objekt PDO, pripojenie k databáze (kód je v Ukážke 2). Riadok 18 pošle do databázy SHOW TABLES a dostane pole názvov tabuliek, napríklad ['categories', 'difficulties', …]. Riadky 21–24 sú zoznam modelov; Ján Novák doň napíše new \App\Model\CategoryModel(),: autoloader načíta src/Model/CategoryModel.php, konštruktor zdedený z BaseModel si vezme to isté pripojenie cez Database::getInstance().

Krok 4. HTML sa vypisuje priamo. Od riadku 26 je HTML stránky s vloženým PHP. Riadok 41 vypíše počet tabuliek, riadky 43–45 ich názvy. Riadky 49–62 pre každý model: describe() dá nadpis (Kategórie), getCount() počet (4), getAll() pole záznamov a array_slice(…, 0, 5) z neho vezme prvých päť; array_keys($rows[0]) dá názvy stĺpcov pre hlavičku tabuľky (id, name), vnorené foreach vypíšu riadky. Každá hodnota ide cez htmlspecialchars(), aby sa prípadné < v dátach zobrazilo ako znak.

Krok 5. Odpoveď. Všetko, čo PHP vypísalo, pošle Apache prehliadaču so stavovým kódom 200 OK. Prehliadač zobrazí nadpis Kontrola projektu, zoznam tabuliek a pre každý model tabuľku s prvými piatimi záznamami.

Najčastejšie chyby a čo znamenajú

Čo vidíš Príčina Riešenie
Class "App\Model\CategoryModel" not found názov súboru sa nezhoduje s menom triedy, alebo v súbore chýba namespace App\Model; skontroluj meno súboru vrátane veľkých písmen a prvý riadok súboru
Failed to open stream: vendor/autoload.php alebo chyba 500 bez textu vendor/ nie je na sigma.tuke.sk composer install v Kubeflow, potom Upload Folder
SQLSTATE[HY000] [1045] Access denied zlý používateľ alebo heslo v config.php porovnaj s prihlásením do Adminer
SQLSTATE[HY000] [1049] Unknown database preklep v dbname názov databázy = tvoj login do Adminer
SQLSTATE[42S02] Base table or view not found schema.sql nebol spustený, alebo $table v modeli má iný názov než CREATE TABLE spusti schema.sql v Adminer; porovnaj $table s CREATE TABLE
SQLSTATE[23000] [1451] Cannot delete or update a parent row mažeš záznam, ktorý používa iná tabuľka s ON DELETE RESTRICT správne správanie; najprv zmaž závislé záznamy
prázdna biela stránka chyba PHP a debug je false v config.php nastav 'debug' => true
chyba 500 po úprave .htaccess preklep v .htaccess vráť pôvodný obsah z kostry

What you get today and what you do with it

You get a skeleton: the file package kostra.zip from the course website (download by clicking, or with the curl command in task 3.2), the same for everyone. The skeleton knows nothing about your topic. You add the SQL for your tables, test data and the classes for your tables.

After unpacking kostra.zip into the folder cv02 in Kubeflow you have these files. Each is explained in the section given:

cv02/
├── composer.json           list for the Composer program: where our classes are       (section 2)
├── .gitignore              list of what Git does not put on GitHub                     (section 2, 5)
├── .htaccess               Apache server settings for this folder                      (section 8)
├── config.example.php      example of the database login details, without a password  (section 5)
├── index.php               check page: lists tables and data                           (Example 5)
├── sql/
│   ├── schema.sql          empty; CREATE TABLE for your tables goes here               (section 6)
│   └── seed.sql            empty; test data goes here                                  (section 6)
└── src/                    our classes
    ├── Database.php        database connection                                         (section 5)
    └── Model/
        ├── ModelInterface.php   list of methods every model must have                  (section 7)
        ├── BaseModel.php        parent of lookup models, ready-made methods             (section 7)
        ├── LookupModel.php      lookup table example – copy and rename                  (section 7)
        └── MainModel.php        main entity example – copy and rename                   (section 7)
Project folder in WinSCP
The same folder in your web space on sigma.tuke.sk, seen through WinSCP. Files starting with a dot (.htaccess, .gitignore) are shown by WinSCP only with hidden files enabled.

A model is a class that works with one database table. For each of your tables (except pivot tables) you will have one file with one class. The examples for it are LookupModel.php and MainModel.php.

Two files are created only on your side: config.php (section 5) and the folder vendor/ (section 2).

The lab procedure:

  1. Unpack kostra.zip into ~/web/it/cv02 in Kubeflow.
  2. In the terminal in cv02 run composer install. The folder vendor/ is created (section 2).
  3. Copy config.example.php to config.php and fill in the database login details (section 5).
  4. Right-click cv02 → Upload Folder. The whole folder is copied to sigma.tuke.sk.
  5. Let the AI create sql/schema.sql and sql/seed.sql from your README and run them in Adminer (section 6).
  6. Let the AI create models for your tables following the examples in the skeleton and add them to index.php (section 7).
  7. Commit and push.

Where the files are:

Place What is there How it gets there
Kubeflow, ~/web/it/cv02 everything: skeleton, vendor/, config.php, your files you write here
sigma.tuke.sk, public_html/it/cv02 the same; the application runs here a file saved in the editor is copied by itself; vendor/ and an unpacked ZIP with Upload Folder
GitHub, repository cv02 skeleton and your files, without vendor/ and config.php git add, commit, push
database on sigma.tuke.sk your tables and data schema.sql and seed.sql run in Adminer

Composer, composer.json, vendor

Composer is a program in Kubeflow, run in the terminal. It follows the file composer.json in the project folder. Today you need it for one thing: so that PHP finds the classes in src/ by itself (section 4).

composer.json is a text file in the JSON format (curly braces, colons, quotation marks). In the skeleton it has these parts:

  • name, description – project name and description; information.
  • require – list of third-party libraries the project needs. It only holds "php": ">=8.1" (PHP at least 8.1), no library.
  • autoload → psr-4 → "App\\": "src/" – the rule where our classes are (section 4).
  • config → platform → "php": "8.1.2" – Composer behaves as if PHP were 8.1.2. Kubeflow has PHP 8.3, sigma.tuke.sk has 8.1; the line prevents downloading anything that would not run on sigma.tuke.sk.

composer install is typed in the Kubeflow terminal in the folder ~/web/it/cv02 (you see the folder before the cursor; if not, cd ~/web/it/cv02). Composer reads composer.json and creates the folder vendor/ in cv02. It contains the file vendor/autoload.php, which index.php loads first (section 4), and Composer’s helper files. You run it after every clone and after every change of composer.json.

Where vendor/ belongs and how you get it there:

  • Kubeflow – it is created here by composer install. Nothing more is needed.
  • sigma.tuke.sk – the application needs it here, because index.php loads vendor/autoload.php. You copy the folder by hand: in Explorer right-click cv02 → Upload Folder. (Files saved in the editor are copied by themselves; vendor/ was created by Composer in the terminal, so the editor does not know about it.) The same after unpacking a ZIP.
  • GitHub – stays out. .gitignore has the line vendor/, so git add skips it. Whoever downloads the repository runs composer install and has it.

composer.lock is created by composer install next to composer.json: the list of exact versions. It goes to GitHub.

More: getcomposer.org: Basic usage

Namespace: the address of a class

Open src/Database.php. After <?php and declare(strict_types=1); there is the line:

namespace App;

A namespace is the address of a class. The full name of a class is address + backslash + name: App\Database. In src/Model/BaseModel.php there is namespace App\Model;, full name App\Model\BaseModel.

What for: the skeleton has the class Database. When you one day add third-party code that also has a class Database, PHP stops with the error “Cannot declare class Database, because the name is already in use”. With addresses they are two names: App\Database and Other\Database.

Using a class from another address: at the top of the file you write use with the full name, then you use the short one:

use App\Database;

$pdo = Database::getInstance();

That is how it is in src/Model/BaseModel.php (what the method getInstance() does is in section 5). PHP’s own classes (for example PDO) have no address; in a file with a namespace you therefore write use PDO;, otherwise PHP would look for App\PDO.

PSR-4: how PHP finds the file with a class

PHP needs a file for the full class name. The rule is in composer.json:

"autoload": { "psr-4": { "App\\": "src/" } }

An address starting with App\ is in the folder src/; the rest of the address is the path; the class name is the file name with .php:

Full class name File
App\Database src/Database.php
App\Model\ModelInterface src/Model/ModelInterface.php
App\Model\BaseModel src/Model/BaseModel.php
App\Model\LookupModel src/Model/LookupModel.php
App\Model\MainModel src/Model/MainModel.php

From this rule Composer generates vendor/autoload.php. In index.php there is the only require in the whole application:

require __DIR__ . '/vendor/autoload.php';

From this line on, whenever PHP meets a class it does not have yet, it builds the path from the address and loads the file by itself. No require_once is written anywhere else.

Two rules for the classes you write in task 3.4: one file = one class; the file name matches the class name including capital letters (CategoryModel.php, class CategoryModel). Otherwise PHP does not find the file.

More: PHP-FIG: PSR-4

config.php and Database.php: login details and the connection

config.php is a file in the project folder with the database login details. You create it in the terminal in cv02:

cp config.example.php config.php

Open config.php in the editor and fill in your details:

config.php
<?php
return [
    'host'   => 'localhost',   // the database runs on the same server as PHP
    'dbname' => 'teacher',     // database name = your Adminer login
    'user'   => 'teacher',     // database login = the same
    'pass'   => 'teacher_psw', // the password from the lab
    'debug'  => true,          // true: PHP errors are shown in the browser
];
Adminer login screen
You enter the same details when signing in to Adminer: System MySQL/MariaDB, Server localhost, User and Database = your login, the password from the lab.

The file returns an array. Whoever needs the details writes $c = require 'config.php'; and has them in $c['host'], $c['user'] and so on.

Where config.php belongs: you create it in Kubeflow; it gets to sigma.tuke.sk by saving in the editor; it stays out of GitHub because it is in .gitignore (the repository only has config.example.php without the password).

src/Database.php creates the database connection. Use from any class:

$pdo = Database::getInstance();

On the first call getInstance() reads config.php, builds the DSN from it (explained below) and creates a PDO object. On every later call it returns the same object. The whole application has one connection. The constructor is private, so new Database() is not possible; the only way is getInstance(). This shape of a class is called a singleton.

A DSN is the string that tells PDO where to connect: mysql:host=localhost;dbname=teacher;charset=utf8mb4. It is built from the values in config.php. The user and the password are given to PDO as two further parameters.

Tables: schema.sql and seed.sql

sql/schema.sql is a text file with CREATE TABLE statements for all tables of your project. sql/seed.sql is a file with INSERT statements with test data. Both are empty in the skeleton. You create them with a prompt (Example 7) from your README and run them in Adminer: SQL command on the left, paste the file content, Execute. First schema.sql, then seed.sql.

Order in schema.sql: a table with a foreign key can be created only when the table it refers to exists. Therefore: lookup tables first, then the main entity, pivot tables last. At the beginning of the file there is DROP TABLE IF EXISTS for every table in reverse order (pivot tables, main entity, lookup tables). The file can thus be run repeatedly: if you break your database, you run both files again.

A table:

CREATE TABLE difficulties (
    id   INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  • id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY – primary key, non-negative integer, assigned by the database.
  • ENGINE=InnoDB – table type that checks foreign keys.
  • CHARSET=utf8mb4 – encoding for Slovak.

A foreign key:

FOREIGN KEY (difficulty_id) REFERENCES difficulties(id) ON DELETE RESTRICT

The ON DELETE rule is the one you justified in the README. Both files are in the repository: whoever opens the project creates the same database.

More: W3Schools: SQL FOREIGN KEY

JOIN: two tables in one query

The table recipes has the column difficulty_id with a number. On the page you want the text “stredný”, which is in the table difficulties. JOIN attaches to every recipe row the difficulty row that belongs to it:

SELECT r.title, r.prep_time, d.name AS difficulty_name
FROM recipes r
JOIN difficulties d ON d.id = r.difficulty_id
ORDER BY r.id DESC;
  • FROM recipes r – we start from the recipes; r is a table alias.
  • JOIN difficulties d ON d.id = r.difficulty_id – to every recipe attach the difficulty whose id equals the recipe’s difficulty_id. After ON there is always “primary key of one table = foreign key of the other”.
  • d.name AS difficulty_name – the column name from the difficulty under another name, so that it is not confused with another name in PHP. $row['difficulty_name'] then holds the text.

What it returns on the sample test data (4 recipes, newest first):

title prep_time difficulty_name
Kari z červenej šošovice 45 náročný
Ovsená kaša s banánom a kakaom 10 ľahký
Tofu na sójovej omáčke s ryžou 25 stredný
Šošovicová polievka s kokosovým mliekom 35 ľahký

Without JOIN the last column would hold only the number difficulty_id (3, 1, 2, 1). You can run the query in Adminer: SQL command, paste, Execute.

JOIN returns only rows that have a partner on the other side. LEFT JOIN returns all rows of the left table even without a partner, with NULL in the right table’s columns.

More: W3Schools: SQL JOIN

Models: classes for tables

OOP terms used in the skeleton:

Term In code What it is
class class LookupModel { } a blueprint: which properties and methods an object has
object $m = new LookupModel(); a concrete thing created from the blueprint
property protected string $table; a variable inside the object
method public function getAll(): array a function of the object; : array is the return type
$this $this->pdo this object, inside its methods
constructor public function __construct() the method that runs on new
public / protected / private access: anybody / the class and its children / the class only
inheritance class LookupModel extends BaseModel the child has everything public and protected from the parent
abstract class abstract class BaseModel a class meant only to be inherited; new BaseModel() is not possible; an abstract method has no body, the child must write it
interface interface ModelInterface, implements a list of methods without code; a class with implements must write them all
static property private static ?PDO $instance belongs to the class, not to an object
?array, ?PDO a value of that type or null

The four files in src/Model/:

ModelInterface.php – the list of methods every model has: getAll(), getById(), getCount(), delete(), describe(). No code. Thanks to it index.php calls describe() and getAll() on every model the same way.

BaseModel.php – an abstract class, the parent of lookup models. It has ready-made getAll(), getById(), getCount(), delete() and a constructor that asks for the connection via Database::getInstance(). The property $table is protected without a value: the child fills it in. The method describe() is abstract: the child writes it.

LookupModel.php – the lookup table example. Its own code is five lines: extends BaseModel, $table = 'lookup_table' and describe(). For each of your lookup tables you copy and rename this file: table categories → file CategoryModel.php, class CategoryModel, $table = 'categories'. Class name: English, singular, suffix Model.

MainModel.php – the main entity example. It does not inherit from BaseModel: its getAll() and getById() have a JOIN to a lookup table, so that they return the text instead of the number. It implements ModelInterface itself, has its own constructor and its own getCount(), delete(), describe(). You copy and rename it the same way; in the SQL you replace main_table, lookup_table, lookup_id with your names.

After creating your own classes you delete the examples LookupModel.php and MainModel.php.

The code of the examples from the skeleton, as you have them in src/Model/ (ModelInterface.php and BaseModel.php are in Example 3):

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

namespace App\Model;

/**
 * VZOR číselníka. Skopíruj tento súbor pre každý svoj číselník a premenuj:
 *   tabuľka categories  ->  súbor CategoryModel.php, trieda CategoryModel, $table = 'categories'
 * Názov triedy je v angličtine, jednotné číslo, končí na Model.
 * Všetko ostatné (getAll, getById, getCount, delete) dedí z BaseModel.
 */
class LookupModel extends BaseModel
{
    protected string $table = 'lookup_table'; // <- názov tvojej tabuľky

    public function describe(): string
    {
        return "Číselník {$this->table}";
    }
}
src/Model/MainModel.php
<?php
declare(strict_types=1);

namespace App\Model;

use App\Database;
use PDO;

/**
 * VZOR hlavnej entity. Skopíruj a premenuj podľa svojej tabuľky:
 *   tabuľka loans  ->  súbor LoanModel.php, trieda LoanModel
 * Hlavná entita nededí z BaseModel: jej dotazy sú iné (JOIN na číselník),
 * preto implementuje ModelInterface samostatne.
 *
 * V SQL dotazoch nahraď:
 *   main_table    názov hlavnej entity (napr. loans)
 *   lookup_table  názov číselníka pripojeného vzťahom 1:N (napr. statuses)
 *   lookup_id     cudzí kľúč na ten číselník (napr. status_id)
 */
class MainModel implements ModelInterface
{
    private PDO $pdo;

    public function __construct()
    {
        $this->pdo = Database::getInstance();
    }

    /** Všetky záznamy aj s názvom z číselníka (JOIN), najnovšie prvé. */
    public function getAll(): array
    {
        $sql = "SELECT m.*, l.name AS lookup_name
                FROM main_table m
                JOIN lookup_table l ON l.id = m.lookup_id
                ORDER BY m.id DESC";
        return $this->pdo->query($sql)->fetchAll();
    }

    public function getById(int $id): ?array
    {
        $sql = "SELECT m.*, l.name AS lookup_name
                FROM main_table m
                JOIN lookup_table l ON l.id = m.lookup_id
                WHERE m.id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch();
        return $row === false ? null : $row;
    }

    public function getCount(): int
    {
        return (int) $this->pdo->query("SELECT COUNT(*) FROM main_table")->fetchColumn();
    }

    public function delete(int $id): bool
    {
        $stmt = $this->pdo->prepare("DELETE FROM main_table WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->rowCount() > 0;
    }

    public function describe(): string
    {
        return 'Hlavná entita main_table';
    }
}

Prepared statement (from OOP): the SQL with the placeholder :id goes to the database separately, the value separately in execute([':id' => $id]). The database processes the value as data, not as SQL. Queries without user input (SELECT * FROM … ORDER BY id) go through query(). The table name in {$this->table} is set by the class, not by the user, so it may be in the string.

.htaccess: server settings for a folder

Apache is the program on sigma.tuke.sk that receives requests from the browser, finds the file in public_html and sends it back; a .php file is run first. .htaccess is a text file with Apache settings for the folder it lies in and its subfolders. Apache reads it on every request; a change applies immediately. An error in it (a typo in a directive) causes error 500 for everything in the folder.

The name starts with a dot: Linux treats it as a hidden file. WinSCP and Explorer in VS Code show it; Windows Explorer may hide it.

.htaccess in the skeleton:

RedirectMatch 404 /(src|vendor|sql|\.git)(/|$)

A request for an address containing /src/, /vendor/, /sql/ or /.git/ gets the answer 404. These folders hold code and SQL, not pages.

<Files "config.php">
    Require all denied
</Files>

A request from the browser for config.php gets the answer 403. PHP loads it normally.

IndexIgnore *

A folder without index.php does not list its files.

Check: in task 3.7 you open …/cv02/src/ and …/cv02/config.php; both must end with error 404 or 403.

More: Apache: .htaccess

How it works: the check page from the address to the table

What Ján Novák wants: to see whether he has tables in the database and whether his models read data. He types https://sigma.tuke.sk/student/jan.novak/it/cv02/ and presses Enter.

Step 1. The browser sends the request GET /student/jan.novak/it/cv02/ to the server sigma.tuke.sk.

Step 2. Apache on sigma.tuke.sk finds the file. The path points to the folder public_html/it/cv02/; the folder contains index.php, Apache runs it. (The .htaccess lines of the skeleton rewrite nothing here; in cv02 the application has a single page.)

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

index.php
<?php
declare(strict_types=1);

// Jediný require v celej aplikácii: Composer odteraz nájde každú triedu sám (PSR-4).
require __DIR__ . '/vendor/autoload.php';

$config = require __DIR__ . '/config.php';
if ($config['debug']) {
    ini_set('display_errors', '1');   // sigma.tuke.sk má chyby vypnuté, počas vývoja ich chceme vidieť
    error_reporting(E_ALL);
}

use App\Database;

$pdo = Database::getInstance();

// 1. Tabuľky, ktoré sú v databáze (po spustení schema.sql).
$tables = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);

// 2. Tvoje modely – po vytvorení tried doplň do zoznamu jeden riadok pre každú:
$models = [
    // new \App\Model\CategoryModel(),
    // new \App\Model\LoanModel(),
];
?>
<!doctype html>
<html lang="sk">
<head>
    <meta charset="utf-8">
    <title>Kontrola projektu</title>
    <style>
        body { font-family: system-ui, sans-serif; max-width: 60rem; margin: 2rem auto; padding: 0 1rem; }
        table { border-collapse: collapse; margin-bottom: 2rem; }
        th, td { border: 1px solid #999; padding: .3rem .6rem; text-align: left; }
        th { background: #eee; }
    </style>
</head>
<body>
<h1>Kontrola projektu</h1>

<h2>Tabuľky v databáze (<?= count($tables) ?>)</h2>
<ul>
    <?php foreach ($tables as $t): ?>
        <li><?= htmlspecialchars($t) ?></li>
    <?php endforeach; ?>
</ul>

<h2>Modely (<?= count($models) ?>)</h2>
<?php foreach ($models as $model): ?>
    <h3><?= htmlspecialchars($model->describe()) ?> – <?= $model->getCount() ?> záznamov</h3>
    <?php $rows = array_slice($model->getAll(), 0, 5); ?>
    <?php if ($rows): ?>
        <table>
            <tr><?php foreach (array_keys($rows[0]) as $col): ?><th><?= htmlspecialchars($col) ?></th><?php endforeach; ?></tr>
            <?php foreach ($rows as $row): ?>
                <tr><?php foreach ($row as $v): ?><td><?= htmlspecialchars((string) $v) ?></td><?php endforeach; ?></tr>
            <?php endforeach; ?>
        </table>
    <?php else: ?>
        <p>Tabuľka je prázdna – spusti seed.sql.</p>
    <?php endif; ?>
<?php endforeach; ?>
</body>
</html>

Line 5 loads vendor/autoload.php from Composer: from this moment PHP finds every class App\… in src/ by itself. Lines 7–11 load config.php and switch on error display. Line 15 calls Database::getInstance(): on the first call it reads config.php, builds the DSN and creates a PDO object, the database connection (the code is in Example 2). Line 18 sends SHOW TABLES to the database and gets an array of table names, for example ['categories', 'difficulties', …]. Lines 21–24 are the list of models; Ján Novák writes new \App\Model\CategoryModel(), into it: the autoloader loads src/Model/CategoryModel.php, the constructor inherited from BaseModel takes the same connection through Database::getInstance().

Step 4. The HTML is printed directly. From line 26 on there is the page HTML with embedded PHP. Line 41 prints the number of tables, lines 43–45 their names. Lines 49–62 for every model: describe() gives the heading (Kategórie), getCount() the count (4), getAll() the array of records and array_slice(…, 0, 5) takes the first five of them; array_keys($rows[0]) gives the column names for the table header (id, name), the nested foreach loops print the rows. Every value goes through htmlspecialchars() so that a < in the data is shown as a character.

Step 5. The response. Everything PHP printed is sent by Apache to the browser with status code 200 OK. The browser shows the heading Kontrola projektu, the list of tables and, for every model, a table with the first five records.

The most common errors and what they mean

What you see Cause Fix
Class "App\Model\CategoryModel" not found the file name does not match the class name, or namespace App\Model; is missing in the file check the file name including capital letters and the first line of the file
Failed to open stream: vendor/autoload.php or a bare error 500 vendor/ is not on sigma.tuke.sk composer install in Kubeflow, then Upload Folder
SQLSTATE[HY000] [1045] Access denied wrong user or password in config.php compare with your Adminer login
SQLSTATE[HY000] [1049] Unknown database typo in dbname database name = your Adminer login
SQLSTATE[42S02] Base table or view not found schema.sql was not run, or $table in the model differs from CREATE TABLE run schema.sql in Adminer; compare $table with CREATE TABLE
SQLSTATE[23000] [1451] Cannot delete or update a parent row you are deleting a record used by another table with ON DELETE RESTRICT correct behaviour; delete the dependent records first
a blank white page a PHP error and debug is false set 'debug' => true in config.php
error 500 after editing .htaccess a typo in .htaccess restore the original content from the skeleton

UkážkyExamples

Ukážka 1: composer.json

composer.json
{
    "name": "tuke/it-projekt",
    "description": "Semestrálny projekt – Informačné technológie",
    "type": "project",
    "require": {
        "php": ">=8.1"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "config": {
        "platform": {
            "php": "8.1.2"
        }
    }
}

Tento súbor v kostre nemeníš.

Ukážka 2: Database.php

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

namespace App;

use PDO;

final class Database
{
    private static ?PDO $instance = null;

    // Súkromný konštruktor: new Database() nie je možné.
    private function __construct()
    {
    }

    public static function getInstance(): PDO
    {
        if (self::$instance === null) {
            $c   = require __DIR__ . '/../config.php';
            $dsn = "mysql:host={$c['host']};dbname={$c['dbname']};charset=utf8mb4";

            self::$instance = new PDO($dsn, $c['user'], $c['pass'], [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]);
        }

        return self::$instance;
    }
}

Čo robí ktorý riadok v Database.php:

  • declare(strict_types=1); – PHP nebude ticho prevádzať typy (reťazec na číslo a pod.); chyba typu sa ozve hneď. Píšeme do každého súboru.
  • namespace App; – adresa triedy; plné meno je App\Database, súbor je src/Database.php.
  • use PDO; – PDO je zabudovaná trieda PHP bez namespace; keďže my sme v namespace App, musíme povedať, že myslíme „tú globálnu”.
  • final class – z triedy sa nedá dediť; pre singleton je to úmysel.
  • private static ?PDO $instance = null; – jediné miesto, kde pripojenie žije. static = patrí triede, nie objektu; ?PDO = PDO alebo null; na začiatku null, lebo pripojenie ešte neexistuje.
  • private function __construct() {} – súkromný konštruktor: new Database() zvonku skončí chybou. Toto robí zo triedy singleton.
  • if (self::$instance === null) – self:: je prístup k statickej vlastnosti vlastnej triedy. Pripojenie sa vytvorí len prvýkrát.
  • require __DIR__ . '/../config.php' – __DIR__ je priečinok tohto súboru (src/), .. ide o úroveň vyššie, kde je config.php. require tu vráti pole z return.
  • new PDO($dsn, $c['user'], $c['pass'], [...]) – samotné pripojenie. Tretí a štvrtý parameter sú používateľ a heslo z config.php.
  • ATTR_ERRMODE => ERRMODE_EXCEPTION – chyba v SQL vyhodí výnimku (PDOException), ktorú vidíš v prehliadači, keď je debug zapnutý; bez toho by chyby zostali ticho.
  • ATTR_DEFAULT_FETCH_MODE => FETCH_ASSOC – riadky z databázy prídu ako asociatívne polia ($row['title']), nie aj s číselnými kľúčmi.
  • ATTR_EMULATE_PREPARES => false – prepared statements rieši databáza, nie PHP; bezpečnejšie a typy sedia.
  • return self::$instance; – vždy to isté PDO.

Ukážka 3: ModelInterface a BaseModel

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

namespace App\Model;

interface ModelInterface
{
    public function getAll(): array;
    public function getById(int $id): ?array;
    public function getCount(): int;
    public function delete(int $id): bool;
    public function describe(): string;
}
src/Model/BaseModel.php
<?php
declare(strict_types=1);

namespace App\Model;

use App\Database;
use PDO;

abstract class BaseModel implements ModelInterface
{
    protected PDO $pdo;
    protected string $table;   // nastaví každý potomok

    public function __construct()
    {
        $this->pdo = Database::getInstance();
    }

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

    public function getById(int $id): ?array
    {
        $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch();
        return $row === false ? null : $row;
    }

    public function getCount(): int
    {
        return (int) $this->pdo->query("SELECT COUNT(*) FROM {$this->table}")->fetchColumn();
    }

    public function delete(int $id): bool
    {
        $stmt = $this->pdo->prepare("DELETE FROM {$this->table} WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->rowCount() > 0;
    }

    abstract public function describe(): string;
}

Čo robí ktorý riadok v BaseModel.php:

  • abstract class BaseModel implements ModelInterface – rodič číselníkov; zaväzuje sa k rozhraniu, ale sám sa nedá vytvoriť.
  • protected PDO $pdo; – pripojenie, ktoré budú používať všetky metódy; protected, aby ho videli aj potomkovia.
  • protected string $table; – názov tabuľky, zámerne bez hodnoty: doplní ho každý potomok.
  • $this->pdo = Database::getInstance(); – v konštruktore si model vypýta spoločné pripojenie. Potomok konštruktor nepíše, zdedí tento.
  • getAll(): query() spustí dotaz bez parametrov, fetchAll() vráti všetky riadky ako pole polí. {$this->table} sa doplní do reťazca.
  • getById(): prepare() pripraví dotaz s :id, execute([':id' => $id]) dosadí hodnotu, fetch() vráti jeden riadok alebo false, keď nič nenašiel. Preto return $row === false ? null : $row; – metóda sľubuje ?array, teda pole alebo null, nie false.
  • getCount(): fetchColumn() vráti prvý stĺpec prvého riadka – pri COUNT(*) priamo číslo; (int) ho prevedie z reťazca na celé číslo, lebo metóda sľubuje int.
  • delete(): po execute() povie rowCount(), koľko riadkov sa zmazalo; > 0 dá true/false. Ak záznam používa iná tabuľka s ON DELETE RESTRICT, databáza zmazanie odmietne a vyhodí výnimku – to je správne správanie, nie chyba kódu.
  • abstract public function describe(): string; – bez tela; každý potomok ju musí napísať.

Ukážka 4: schema.sql a seed.sql vzorového projektu

Tabuľky receptov z 2. týždňa, v poradí, v akom sa dajú vytvoriť. Všimni si, že DROP TABLE ide v opačnom poradí ako CREATE TABLE.

sql/schema.sql
-- Mazanie v opačnom poradí: najprv prepojky, potom hlavná entita, nakoniec číselníky.
DROP TABLE IF EXISTS recipe_ingredients;
DROP TABLE IF EXISTS recipe_categories;
DROP TABLE IF EXISTS recipes;
DROP TABLE IF EXISTS units;
DROP TABLE IF EXISTS ingredients;
DROP TABLE IF EXISTS categories;
DROP TABLE IF EXISTS difficulties;

-- Číselník: obtiažnosť receptu (ľahký, stredný, náročný).
CREATE TABLE difficulties (
    id   INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Číselník: kategória jedla (polievka, hlavné jedlo, dezert).
CREATE TABLE categories (
    id   INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Číselník: surovina.
CREATE TABLE ingredients (
    id   INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Číselník: merná jednotka (g, ml, ks).
CREATE TABLE units (
    id           INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name         VARCHAR(30) NOT NULL,
    abbreviation VARCHAR(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Hlavná entita: recept.
CREATE TABLE recipes (
    id            INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    title         VARCHAR(120) NOT NULL,
    servings      TINYINT UNSIGNED NOT NULL DEFAULT 4,
    prep_time     SMALLINT UNSIGNED NOT NULL,          -- minúty
    instructions  TEXT NOT NULL,
    created_at    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    difficulty_id INT UNSIGNED NOT NULL,
    -- 1:N na číselník. RESTRICT: obtiažnosť sa nedá zmazať, kým ju používa recept.
    FOREIGN KEY (difficulty_id) REFERENCES difficulties(id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Prepojka bez atribútov: recept × kategória.
CREATE TABLE recipe_categories (
    recipe_id   INT UNSIGNED NOT NULL,
    category_id INT UNSIGNED NOT NULL,
    PRIMARY KEY (recipe_id, category_id),
    -- CASCADE: so zmazaným receptom zmiznú aj jeho prepojenia.
    FOREIGN KEY (recipe_id)   REFERENCES recipes(id)    ON DELETE CASCADE,
    -- RESTRICT: kategória sa nedá zmazať, kým ju používa recept.
    FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Prepojka s atribútmi: recept × surovina, s množstvom a jednotkou.
CREATE TABLE recipe_ingredients (
    recipe_id     INT UNSIGNED NOT NULL,
    ingredient_id INT UNSIGNED NOT NULL,
    amount        DECIMAL(8,2) NOT NULL,
    note          VARCHAR(100) NULL,
    unit_id       INT UNSIGNED NOT NULL,
    PRIMARY KEY (recipe_id, ingredient_id),
    FOREIGN KEY (recipe_id)     REFERENCES recipes(id)     ON DELETE CASCADE,
    FOREIGN KEY (ingredient_id) REFERENCES ingredients(id) ON DELETE RESTRICT,
    FOREIGN KEY (unit_id)       REFERENCES units(id)       ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Testovacie dáta v rovnakom poradí: číselníky, hlavná entita, prepojky. Cudzie kľúče odkazujú na id, ktoré už existujú:

sql/seed.sql
INSERT INTO difficulties (id, name) VALUES
(1, 'ľahký'), (2, 'stredný'), (3, 'náročný');

INSERT INTO categories (id, name) VALUES
(1, 'polievka'), (2, 'hlavné jedlo'), (3, 'dezert'), (4, 'raňajky');

INSERT INTO units (id, name, abbreviation) VALUES
(1, 'gram', 'g'), (2, 'mililiter', 'ml'), (3, 'kus', 'ks'), (4, 'lyžica', 'PL');

INSERT INTO ingredients (id, name) VALUES
(1, 'červená šošovica'), (2, 'cibuľa'), (3, 'cesnak'), (5, 'kokosové mlieko'), (6, 'tofu');

INSERT INTO recipes (id, title, servings, prep_time, instructions, difficulty_id) VALUES
(1, 'Šošovicová polievka s kokosovým mliekom', 4, 35, 'Na oleji opražíme cibuľu a cesnak …', 1),
(2, 'Tofu na sójovej omáčke s ryžou', 2, 25, 'Tofu nakrájame na kocky …', 2);

INSERT INTO recipe_categories (recipe_id, category_id) VALUES
(1, 1), (2, 2);

INSERT INTO recipe_ingredients (recipe_id, ingredient_id, amount, note, unit_id) VALUES
(1, 1, 200, NULL, 1), (1, 2, 1, 'nadrobno', 3), (1, 5, 200, NULL, 2),
(2, 6, 300, NULL, 1), (2, 3, 1, NULL, 3);

(Skrátené; celý súbor je vo vzore so 4 receptami a 14 surovinami.)

Adminer SQL command po spustení schema.sql
Spustenie schema.sql: vľavo SQL command, vložiť celý obsah súboru, Execute. Adminer vypíše každý príkaz a pod ním zelené „Príkaz prebehol v poriadku“. Pri CREATE TABLE je „zmenených 0 záznamov“ správne – tabuľka vznikla, dáta ešte nie.
Adminer: zoznam siedmich tabuliek
Po schema.sql je v ľavom paneli 7 tabuliek, všetky InnoDB a utf8mb4_unicode_ci.
Adminer: štruktúra tabuľky recipes
Zobraziť štruktúru pri recipes: stĺpce s typmi, index na difficulty_id (databáza ho pre cudzí kľúč vytvorí sama) a dole cudzí kľúč s pravidlom RESTRICT „Pri zmazaní“.
Adminer: štruktúra prepojky recipe_ingredients
Prepojka s atribútmi: primárny kľúč zložený z recipe_id a ingredient_id, tri cudzie kľúče – na recept CASCADE, na surovinu a jednotku RESTRICT. Presne podľa README.
Adminer: chyba 1451 pri pokuse zmazať obtiažnosť
Čo urobí RESTRICT naživo: označiť riadok „stredný“ v difficulties, Zmazať – databáza odmietne: Cannot delete or update a parent row: a foreign key constraint fails, lebo recept č. 2 túto obtiažnosť používa. To nie je chyba, to je ochrana dát.

Ukážka 5: modely vzorového projektu a index.php

Číselník má päť riadkov vlastného kódu. Hlavná entita nededí: jej dotazy majú JOIN na názov obtiažnosti.

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

namespace App\Model;

class DifficultyModel extends BaseModel
{
    protected string $table = 'difficulties';

    public function describe(): string
    {
        return 'Číselník obtiažností';
    }
}
src/Model/RecipeModel.php
<?php
declare(strict_types=1);

namespace App\Model;

use App\Database;
use PDO;

class RecipeModel implements ModelInterface
{
    private PDO $pdo;

    public function __construct()
    {
        $this->pdo = Database::getInstance();
    }

    // Recepty aj s názvom obtiažnosti, najnovšie prvé.
    public function getAll(): array
    {
        $sql = "SELECT r.*, d.name AS difficulty_name
                FROM recipes r
                JOIN difficulties d ON d.id = r.difficulty_id
                ORDER BY r.id DESC";
        return $this->pdo->query($sql)->fetchAll();
    }

    public function getById(int $id): ?array
    {
        $sql = "SELECT r.*, d.name AS difficulty_name
                FROM recipes r
                JOIN difficulties d ON d.id = r.difficulty_id
                WHERE r.id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch();
        return $row === false ? null : $row;
    }

    public function getCount(): int
    {
        return (int) $this->pdo->query("SELECT COUNT(*) FROM recipes")->fetchColumn();
    }

    public function delete(int $id): bool
    {
        $stmt = $this->pdo->prepare("DELETE FROM recipes WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->rowCount() > 0;
    }

    public function describe(): string
    {
        return 'Recepty';
    }
}

Čo robí ktorý riadok v modeloch:

  • DifficultyModel extends BaseModel – zdedí konštruktor, $pdo a štyri metódy. protected string $table = 'difficulties'; doplní hodnotu, ktorú rodič nechal prázdnu. describe() je jediná metóda, ktorú musí napísať, lebo v rodičovi je abstraktná. Celá trieda má päť riadkov vlastného kódu – to je zmysel dedenia.
  • RecipeModel implements ModelInterface – nededí, preto má vlastné private PDO $pdo; (tu môže byť private, nikto z nej nededí) a vlastný konštruktor, ktorý si vypýta pripojenie rovnako ako BaseModel.
  • SELECT r.*, d.name AS difficulty_name FROM recipes r JOIN difficulties d ON d.id = r.difficulty_id – r a d sú skratky (aliasy) tabuliek. r.* = všetky stĺpce receptu, d.name AS difficulty_name = k tomu názov obtiažnosti pod zrozumiteľným menom. JOIN … ON spojí riadok receptu s riadkom obtiažnosti, ktorý má rovnaké id ako difficulty_id. Vo výsledku je $row['difficulty_name'] = „stredná” namiesto čísla 2.
  • ORDER BY r.id DESC – najnovšie recepty prvé; číselníky majú ORDER BY id, lebo poradie vloženia je aj poradie zobrazenia.
  • getById() s tým istým JOIN a WHERE r.id = :id – pri aliasoch treba povedať, ktorej tabuľky id myslíme.
  • getCount() a delete() sú rovnaké ako v BaseModel, len s pevným názvom tabuľky.

Čo metódy vrátia na testovacích dátach vzoru:

Volanie Výsledok
$m->getCount() 4 (celé číslo)
$m->getById(2) pole: ['id' => 2, 'title' => 'Tofu na sójovej omáčke s ryžou', 'servings' => 2, 'prep_time' => 25, …, 'difficulty_id' => 2, 'difficulty_name' => 'stredný']
$m->getById(99) null – záznam neexistuje, fetch() vrátil false
$m->getAll() pole štyroch takých polí, v poradí id 4, 3, 2, 1
(new DifficultyModel())->getAll() [['id' => 1, 'name' => 'ľahký'], ['id' => 2, 'name' => 'stredný'], ['id' => 3, 'name' => 'náročný']]

V index.php sa modely použijú rovnako, bez ohľadu na to, či dedia alebo nie:

$models = [
    new \App\Model\DifficultyModel(),
    new \App\Model\CategoryModel(),
    new \App\Model\RecipeModel(),
];

Čo robí index.php z kostry (kontrolná stránka); celý súbor je v časti „Ako to funguje: kontrolná stránka od adresy po tabuľku“:

  • require __DIR__ . '/vendor/autoload.php'; (riadok 5) – jediný require v aplikácii; od tohto riadka PHP nájde každú triedu App\… samo.
  • $config = require __DIR__ . '/config.php'; a if ($config['debug']) { ini_set('display_errors', '1'); error_reporting(E_ALL); } (riadky 7–11) – sigma.tuke.sk má zobrazovanie chýb vypnuté; počas vývoja ich chceme vidieť, preto ich zapneme, keď je v konfigurácii debug na true.
  • use App\Database; a $pdo = Database::getInstance(); – prvé a jediné vytvorenie pripojenia; modely dostanú to isté.
  • $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN) – zoznam tabuliek v databáze ako jednoduché pole názvov; funguje ešte pred tým, než máš akýkoľvek model.
  • $models = [ new \App\Model\CategoryModel(), … ]; – zoznam tvojich modelov; doplníš jeden riadok na triedu. Plné meno s \ na začiatku preto, že index.php nie je v žiadnom namespace a use sme použili len pre Database.
  • foreach ($models as $model) – pre každý model describe(), getCount() a prvých päť riadkov z getAll() cez array_slice. Hlavičku tabuľky vyrobí array_keys($rows[0]) – názvy stĺpcov z prvého riadka.
  • htmlspecialchars(...) pri každom výpise – hodnoty z databázy sa nevypisujú priamo, aby prípadné < v dátach nerozbilo stránku; ochrana pred vložením cudzieho HTML do stránky (XSS).
Kontrolná stránka: výpis modelu Recepty
Čo uvidíš v prehliadači pri modeli RecipeModel: nadpis z describe() s počtom z getCount() a tabuľka prvých riadkov z getAll(). Posledný stĺpec difficulty_name je výsledok JOIN; stĺpce ostatných modelov sú len id a name.

Ukážka 6: .htaccess kostry

.htaccess
# Priečinky s kódom a SQL nie sú stránky: požiadavka na ne dostane 404.
RedirectMatch 404 /(src|vendor|sql|\.git)(/|$)

# Súbor s heslom k databáze sa cez prehliadač nedá otvoriť (403).
<Files "config.php">
    Require all denied
</Files>

# Priečinok bez index.php nevypíše svoj obsah.
IndexIgnore *

Takto má skončiť pokus otvoriť …/cv02/src/ v prehliadači:

Prehliadač: Not Found pre priečinok src
Kód leží na serveri, ale web server ho nevydá.

Ukážka 7: prompt na tabuľky a testovacie dáta

Nižšie je dátový model mojej aplikácie (tabuľky, stĺpce, vzťahy, pravidlá ON DELETE).
Vyrob z neho dva súbory pre MariaDB 10.6.

1. schema.sql
- Na začiatku DROP TABLE IF EXISTS pre všetky tabuľky v poradí, v akom sa dajú zmazať
  (prepojky, potom hlavná entita, potom číselníky).
- CREATE TABLE v poradí, v akom sa dajú vytvoriť (číselníky, hlavná entita, prepojky).
- Každá tabuľka: ENGINE=InnoDB, DEFAULT CHARSET=utf8mb4, COLLATE=utf8mb4_unicode_ci.
- Primárny kľúč: id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY.
- Cudzie kľúče ako FOREIGN KEY ... REFERENCES ... s pravidlom ON DELETE presne podľa modelu.
- Pri každej tabuľke a každom cudzom kľúči krátky SQL komentár (-- ...) po slovensky,
  čo tabuľka drží a prečo platí dané pravidlo ON DELETE.
- Nepíš CREATE DATABASE ani USE.

2. seed.sql
- INSERT do každej tabuľky, 3 až 5 riadkov, zmysluplné hodnoty po slovensky k mojej téme.
- Poradie vkladania: číselníky, hlavná entita, prepojky; cudzie kľúče odkazujú na existujúce id.

Dátový model:
[SEM VLOŽ DÁTOVÝ MODEL Z README]

Prečo je prompt napísaný práve takto:

  • Poradie mazania a vytvárania je vymenované, lebo AI ho pri prepojkách často preto hodí a schema.sql potom padne na cudzom kľúči.
  • ENGINE, CHARSET a tvar primárneho kľúča sú predpísané, aby všetky tabuľky v skupine vyzerali rovnako a dali sa porovnávať so vzorom.
  • Komentáre pri ON DELETE žiadame preto, že pri obhajobe vysvetľuješ každé pravidlo.
  • CREATE DATABASE a USE zakazujeme, lebo databázu už máš a cudzia by na sigma.tuke.sk nešla vytvoriť.
  • Seed s reálnymi hodnotami k tvojej téme: stránka s výpisom má o čom hovoriť a pri obhajobe vidno, že dátam rozumieš.

Ukážka 8: prompt na modely

Prikladám kostru PHP projektu (namespace App\Model, autoload PSR-4 cez Composer):
ModelInterface.php, BaseModel.php, LookupModel.php (vzor číselníka), MainModel.php
(vzor hlavnej entity) a svoj schema.sql.

Vyrob pre moje tabuľky triedy modelov, pre každú jeden súbor do src/Model/:
- pre každý číselník triedu podľa vzoru LookupModel: extends BaseModel, nastav $table,
  describe() vráti krátky popis po slovensky; nič iné nepridávaj,
- pre hlavnú entitu triedu podľa vzoru MainModel: implements ModelInterface, getAll() a
  getById() s JOIN na číselník pripojený vzťahom 1:N (vráť aj jeho name pod zrozumiteľným
  aliasom), getCount(), delete(), describe(); prepared statements s pomenovanými
  placeholdermi.
Názvy tried: anglicky, jednotné číslo, prípona Model (categories -> CategoryModel).
Každá trieda má PHP 8.1 syntax: declare(strict_types=1), typy parametrov a návratových hodnôt.
Nad každou metódou jednoriadkový komentár po slovensky, čo robí.
Na konci napíš riadky, ktoré mám vložiť do poľa $models v index.php.

[SEM VLOŽ OBSAH ŠTYROCH SÚBOROV KOSTRY A SCHEMA.SQL]

Prečo je prompt napísaný práve takto:

  • Prikladáš kostru, nie opis kostry: AI vidí presný namespace, mená metód a štýl, a výsledok do kostry zapadne bez úprav.
  • „Nič iné nepridávaj” pri číselníkoch bráni tomu, aby AI do päťriadkovej triedy dopísala vlastné getAll() a dedenie stratilo zmysel.
  • Pravidlo pre názvy tried je tu preto, že názov súboru musí sedieť s menom triedy, inak PSR-4 autoloader súbor nenájde.
  • PHP 8.1 je uvedené výslovne, lebo AI inak rado použije novšie konštrukcie, ktoré na sigma.tuke.sk nebežia.
  • Riadky pre $models na konci ušetria preklepy v plných menách tried.

Example 1: composer.json

composer.json
{
    "name": "tuke/it-projekt",
    "description": "Semester project – Information Technologies",
    "type": "project",
    "require": {
        "php": ">=8.1"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "config": {
        "platform": {
            "php": "8.1.2"
        }
    }
}

You do not change this file in the skeleton.

Example 2: Database.php

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

namespace App;

use PDO;

final class Database
{
    private static ?PDO $instance = null;

    // Private constructor: new Database() is not possible.
    private function __construct()
    {
    }

    public static function getInstance(): PDO
    {
        if (self::$instance === null) {
            $c   = require __DIR__ . '/../config.php';
            $dsn = "mysql:host={$c['host']};dbname={$c['dbname']};charset=utf8mb4";

            self::$instance = new PDO($dsn, $c['user'], $c['pass'], [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]);
        }

        return self::$instance;
    }
}

What each line in Database.php does:

  • declare(strict_types=1); – PHP will not silently convert types (string to number etc.); a type error shows up immediately. We write it in every file.
  • namespace App; – the class address; the full name is App\Database, the file is src/Database.php.
  • use PDO; – PDO is a built-in PHP class without a namespace; since we are inside the namespace App, we have to say we mean “the global one”.
  • final class – the class cannot be inherited from; for a singleton that is intentional.
  • private static ?PDO $instance = null; – the only place where the connection lives. static = belongs to the class, not to an object; ?PDO = PDO or null; null at the start because the connection does not exist yet.
  • private function __construct() {} – private constructor: new Database() from outside ends with an error. This is what makes the class a singleton.
  • if (self::$instance === null) – self:: accesses a static property of the class itself. The connection is created only the first time.
  • require __DIR__ . '/../config.php' – __DIR__ is the folder of this file (src/), .. goes one level up, where config.php is. require here returns the array from return.
  • new PDO($dsn, $c['user'], $c['pass'], [...]) – the connection itself. The third and fourth parameters are the user and the password from config.php.
  • ATTR_ERRMODE => ERRMODE_EXCEPTION – an SQL error throws an exception (PDOException), which you see in the browser when debug is on; without it errors would stay silent.
  • ATTR_DEFAULT_FETCH_MODE => FETCH_ASSOC – rows from the database come as associative arrays ($row['title']), without numeric keys as well.
  • ATTR_EMULATE_PREPARES => false – prepared statements are handled by the database, not by PHP; safer and the types match.
  • return self::$instance; – always the same PDO.

Example 3: ModelInterface and BaseModel

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

namespace App\Model;

interface ModelInterface
{
    public function getAll(): array;
    public function getById(int $id): ?array;
    public function getCount(): int;
    public function delete(int $id): bool;
    public function describe(): string;
}
src/Model/BaseModel.php
<?php
declare(strict_types=1);

namespace App\Model;

use App\Database;
use PDO;

abstract class BaseModel implements ModelInterface
{
    protected PDO $pdo;
    protected string $table;   // set by every child

    public function __construct()
    {
        $this->pdo = Database::getInstance();
    }

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

    public function getById(int $id): ?array
    {
        $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch();
        return $row === false ? null : $row;
    }

    public function getCount(): int
    {
        return (int) $this->pdo->query("SELECT COUNT(*) FROM {$this->table}")->fetchColumn();
    }

    public function delete(int $id): bool
    {
        $stmt = $this->pdo->prepare("DELETE FROM {$this->table} WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->rowCount() > 0;
    }

    abstract public function describe(): string;
}

What each line in BaseModel.php does:

  • abstract class BaseModel implements ModelInterface – the parent of lookup models; it commits to the interface but cannot be created itself.
  • protected PDO $pdo; – the connection all methods will use; protected so that children see it too.
  • protected string $table; – the table name, deliberately without a value: every child fills it in.
  • $this->pdo = Database::getInstance(); – in the constructor the model asks for the shared connection. The child does not write a constructor; it inherits this one.
  • getAll(): query() runs a query without parameters, fetchAll() returns all rows as an array of arrays. {$this->table} is inserted into the string.
  • getById(): prepare() prepares the query with :id, execute([':id' => $id]) supplies the value, fetch() returns one row or false when nothing was found. Hence return $row === false ? null : $row; – the method promises ?array, i.e. an array or null, not false.
  • getCount(): fetchColumn() returns the first column of the first row – with COUNT(*) that is the number itself; (int) converts it from a string to an integer, because the method promises int.
  • delete(): after execute(), rowCount() says how many rows were deleted; > 0 gives true/false. If another table uses the record with ON DELETE RESTRICT, the database refuses the delete and throws an exception – that is correct behaviour, not a bug.
  • abstract public function describe(): string; – without a body; every child must write it.

Example 4: schema.sql and seed.sql of the sample project

The recipe tables from week 2, in the order they can be created. Note that DROP TABLE goes in the reverse order of CREATE TABLE.

sql/schema.sql
-- Dropping in reverse order: pivot tables first, then the main entity, lookup tables last.
DROP TABLE IF EXISTS recipe_ingredients;
DROP TABLE IF EXISTS recipe_categories;
DROP TABLE IF EXISTS recipes;
DROP TABLE IF EXISTS units;
DROP TABLE IF EXISTS ingredients;
DROP TABLE IF EXISTS categories;
DROP TABLE IF EXISTS difficulties;

-- Lookup table: recipe difficulty (easy, medium, hard).
CREATE TABLE difficulties (
    id   INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Lookup table: meal category (soup, main course, dessert).
CREATE TABLE categories (
    id   INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Lookup table: ingredient.
CREATE TABLE ingredients (
    id   INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Lookup table: unit of measure (g, ml, pcs).
CREATE TABLE units (
    id           INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name         VARCHAR(30) NOT NULL,
    abbreviation VARCHAR(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Main entity: recipe.
CREATE TABLE recipes (
    id            INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    title         VARCHAR(120) NOT NULL,
    servings      TINYINT UNSIGNED NOT NULL DEFAULT 4,
    prep_time     SMALLINT UNSIGNED NOT NULL,          -- minutes
    instructions  TEXT NOT NULL,
    created_at    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    difficulty_id INT UNSIGNED NOT NULL,
    -- 1:N to a lookup table. RESTRICT: a difficulty cannot be deleted while a recipe uses it.
    FOREIGN KEY (difficulty_id) REFERENCES difficulties(id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Pivot table without attributes: recipe × category.
CREATE TABLE recipe_categories (
    recipe_id   INT UNSIGNED NOT NULL,
    category_id INT UNSIGNED NOT NULL,
    PRIMARY KEY (recipe_id, category_id),
    -- CASCADE: when a recipe is deleted, its links go with it.
    FOREIGN KEY (recipe_id)   REFERENCES recipes(id)    ON DELETE CASCADE,
    -- RESTRICT: a category cannot be deleted while a recipe uses it.
    FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Pivot table with attributes: recipe × ingredient, with amount and unit.
CREATE TABLE recipe_ingredients (
    recipe_id     INT UNSIGNED NOT NULL,
    ingredient_id INT UNSIGNED NOT NULL,
    amount        DECIMAL(8,2) NOT NULL,
    note          VARCHAR(100) NULL,
    unit_id       INT UNSIGNED NOT NULL,
    PRIMARY KEY (recipe_id, ingredient_id),
    FOREIGN KEY (recipe_id)     REFERENCES recipes(id)     ON DELETE CASCADE,
    FOREIGN KEY (ingredient_id) REFERENCES ingredients(id) ON DELETE RESTRICT,
    FOREIGN KEY (unit_id)       REFERENCES units(id)       ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Test data in the same order: lookup tables, main entity, pivot tables. Foreign keys refer to ids that already exist:

sql/seed.sql
INSERT INTO difficulties (id, name) VALUES
(1, 'ľahký'), (2, 'stredný'), (3, 'náročný');

INSERT INTO categories (id, name) VALUES
(1, 'polievka'), (2, 'hlavné jedlo'), (3, 'dezert'), (4, 'raňajky');

INSERT INTO units (id, name, abbreviation) VALUES
(1, 'gram', 'g'), (2, 'mililiter', 'ml'), (3, 'kus', 'ks'), (4, 'lyžica', 'PL');

INSERT INTO ingredients (id, name) VALUES
(1, 'červená šošovica'), (2, 'cibuľa'), (3, 'cesnak'), (5, 'kokosové mlieko'), (6, 'tofu');

INSERT INTO recipes (id, title, servings, prep_time, instructions, difficulty_id) VALUES
(1, 'Šošovicová polievka s kokosovým mliekom', 4, 35, 'Na oleji opražíme cibuľu a cesnak …', 1),
(2, 'Tofu na sójovej omáčke s ryžou', 2, 25, 'Tofu nakrájame na kocky …', 2);

INSERT INTO recipe_categories (recipe_id, category_id) VALUES
(1, 1), (2, 2);

INSERT INTO recipe_ingredients (recipe_id, ingredient_id, amount, note, unit_id) VALUES
(1, 1, 200, NULL, 1), (1, 2, 1, 'nadrobno', 3), (1, 5, 200, NULL, 2),
(2, 6, 300, NULL, 1), (2, 3, 1, NULL, 3);

(Shortened; the full file in the sample has 4 recipes and 14 ingredients.)

Adminer SQL command after running schema.sql
Running schema.sql: SQL command on the left, paste the whole file, Execute. Adminer prints every statement with a green “Query executed OK” under it. For CREATE TABLE “0 rows affected” is correct – the table was created, there is no data yet.
Adminer: list of seven tables
After schema.sql the left panel shows 7 tables, all InnoDB and utf8mb4_unicode_ci.
Adminer: structure of the recipes table
Show structure of recipes: columns with types, an index on difficulty_id (the database creates it for the foreign key by itself) and at the bottom the foreign key with the RESTRICT rule “On delete”.
Adminer: structure of the recipe_ingredients pivot table
A pivot table with attributes: a primary key made of recipe_id and ingredient_id, three foreign keys – CASCADE to the recipe, RESTRICT to the ingredient and the unit. Exactly as in the README.
Adminer: error 1451 when trying to delete a difficulty
RESTRICT live: select the row “stredný” in difficulties, Delete – the database refuses: Cannot delete or update a parent row: a foreign key constraint fails, because recipe no. 2 uses this difficulty. That is not an error, that is data protection.

Example 5: the sample project’s models and index.php

A lookup model has five lines of its own code. The main entity does not inherit: its queries have a JOIN for the difficulty name.

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

namespace App\Model;

class DifficultyModel extends BaseModel
{
    protected string $table = 'difficulties';

    public function describe(): string
    {
        return 'Difficulty lookup table';
    }
}
src/Model/RecipeModel.php
<?php
declare(strict_types=1);

namespace App\Model;

use App\Database;
use PDO;

class RecipeModel implements ModelInterface
{
    private PDO $pdo;

    public function __construct()
    {
        $this->pdo = Database::getInstance();
    }

    // Recipes with the difficulty name, newest first.
    public function getAll(): array
    {
        $sql = "SELECT r.*, d.name AS difficulty_name
                FROM recipes r
                JOIN difficulties d ON d.id = r.difficulty_id
                ORDER BY r.id DESC";
        return $this->pdo->query($sql)->fetchAll();
    }

    public function getById(int $id): ?array
    {
        $sql = "SELECT r.*, d.name AS difficulty_name
                FROM recipes r
                JOIN difficulties d ON d.id = r.difficulty_id
                WHERE r.id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch();
        return $row === false ? null : $row;
    }

    public function getCount(): int
    {
        return (int) $this->pdo->query("SELECT COUNT(*) FROM recipes")->fetchColumn();
    }

    public function delete(int $id): bool
    {
        $stmt = $this->pdo->prepare("DELETE FROM recipes WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->rowCount() > 0;
    }

    public function describe(): string
    {
        return 'Recipes';
    }
}

What each line in the models does:

  • DifficultyModel extends BaseModel – inherits the constructor, $pdo and the four methods. protected string $table = 'difficulties'; fills in the value the parent left empty. describe() is the only method it must write, because it is abstract in the parent. The whole class has five lines of its own code – that is the point of inheritance.
  • RecipeModel implements ModelInterface – does not inherit, so it has its own private PDO $pdo; (it may be private here, nobody inherits from it) and its own constructor, which asks for the connection just like BaseModel.
  • SELECT r.*, d.name AS difficulty_name FROM recipes r JOIN difficulties d ON d.id = r.difficulty_id – r and d are table aliases. r.* = all columns of the recipe, d.name AS difficulty_name = plus the difficulty name under a readable name. JOIN … ON pairs the recipe row with the difficulty row whose id equals difficulty_id. In the result $row['difficulty_name'] is “medium” instead of the number 2.
  • ORDER BY r.id DESC – newest recipes first; lookup tables use ORDER BY id, because insertion order is also display order.
  • getById() with the same JOIN and WHERE r.id = :id – with aliases you must say which table’s id you mean.
  • getCount() and delete() are the same as in BaseModel, only with a fixed table name.

What the methods return on the sample test data:

Call Result
$m->getCount() 4 (integer)
$m->getById(2) array: ['id' => 2, 'title' => 'Tofu na sójovej omáčke s ryžou', 'servings' => 2, 'prep_time' => 25, …, 'difficulty_id' => 2, 'difficulty_name' => 'stredný']
$m->getById(99) null – the record does not exist, fetch() returned false
$m->getAll() an array of four such arrays, in the order id 4, 3, 2, 1
(new DifficultyModel())->getAll() [['id' => 1, 'name' => 'ľahký'], ['id' => 2, 'name' => 'stredný'], ['id' => 3, 'name' => 'náročný']]

In index.php the models are then used the same way, whether they inherit or not:

$models = [
    new \App\Model\DifficultyModel(),
    new \App\Model\CategoryModel(),
    new \App\Model\RecipeModel(),
];

What the skeleton’s index.php (the check page) does; the whole file is in the part “How it works: the check page from the address to the table”:

  • require __DIR__ . '/vendor/autoload.php'; (line 5) – the only require in the application; from this line on PHP finds every class App\… by itself.
  • $config = require __DIR__ . '/config.php'; and if ($config['debug']) { ini_set('display_errors', '1'); error_reporting(E_ALL); } (lines 7–11) – sigma.tuke.sk has error display switched off; during development we want to see errors, so we switch them on when debug is true in the configuration.
  • use App\Database; and $pdo = Database::getInstance(); – the first and only creation of the connection; the models get the same one.
  • $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN) – the list of tables in the database as a plain array of names; works even before you have any model.
  • $models = [ new \App\Model\CategoryModel(), … ]; – the list of your models; you add one line per class. The full name with a leading \ because index.php is in no namespace and we used use only for Database.
  • foreach ($models as $model) – for every model describe(), getCount() and the first five rows of getAll() via array_slice. The table header comes from array_keys($rows[0]) – the column names of the first row.
  • htmlspecialchars(...) at every output – values from the database are not printed directly, so that a < in the data cannot break the page; protection against inserting foreign HTML into the page (XSS).
Check page: listing of the Recipes model
What you see in the browser for RecipeModel: the heading from describe() with the count from getCount() and a table of the first rows from getAll(). The last column difficulty_name is the result of the JOIN; the other models have only id and name.

Example 6: the skeleton’s .htaccess

.htaccess
# Folders with code and SQL are not pages: a request for them gets 404.
RedirectMatch 404 /(src|vendor|sql|\.git)(/|$)

# The file with the database password cannot be opened in the browser (403).
<Files "config.php">
    Require all denied
</Files>

# A folder without index.php does not list its contents.
IndexIgnore *

This is how an attempt to open …/cv02/src/ in the browser must end:

Browser: Not Found for the src folder
The code is on the server, but the web server does not serve it.

Example 7: the prompt for tables and test data

Below is the data model of my application (tables, columns, relationships, ON DELETE rules).
Create two files from it for MariaDB 10.6.

1. schema.sql
- At the beginning DROP TABLE IF EXISTS for all tables in the order they can be dropped
  (pivot tables, then the main entity, then lookup tables).
- CREATE TABLE in the order they can be created (lookup tables, main entity, pivot tables).
- Every table: ENGINE=InnoDB, DEFAULT CHARSET=utf8mb4, COLLATE=utf8mb4_unicode_ci.
- Primary key: id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY.
- Foreign keys as FOREIGN KEY ... REFERENCES ... with the ON DELETE rule exactly as in the model.
- A short SQL comment (-- ...) at every table and every foreign key saying what the table holds
  and why the given ON DELETE rule applies.
- Do not write CREATE DATABASE or USE.

2. seed.sql
- INSERT into every table, 3 to 5 rows, meaningful values for my topic.
- Insert order: lookup tables, main entity, pivot tables; foreign keys refer to existing ids.

Data model:
[PASTE THE DATA MODEL FROM YOUR README HERE]

Why the prompt is written this way:

  • The drop and create order is spelled out, because the AI often gets it wrong with pivot tables and schema.sql then fails on a foreign key.
  • ENGINE, CHARSET and the primary key form are prescribed so that all tables in the group look the same and can be compared with the sample.
  • We ask for comments at ON DELETE because you explain every rule at the defence.
  • CREATE DATABASE and USE are forbidden because you already have a database and another one could not be created on sigma.tuke.sk.
  • Seed data with real values for your topic: the listing page has something to show and at the defence it is clear you understand the data.

Example 8: the prompt for models

Attached is the skeleton of a PHP project (namespace App\Model, PSR-4 autoload via Composer):
ModelInterface.php, BaseModel.php, LookupModel.php (lookup table example), MainModel.php
(main entity example) and my schema.sql.

Create model classes for my tables, one file each into src/Model/:
- for every lookup table a class following LookupModel: extends BaseModel, set $table,
  describe() returns a short description; add nothing else,
- for the main entity a class following MainModel: implements ModelInterface, getAll() and
  getById() with a JOIN to the lookup table connected by the 1:N relationship (return its name
  under a readable alias), getCount(), delete(), describe(); prepared statements with named
  placeholders.
Class names: English, singular, suffix Model (categories -> CategoryModel).
Every class uses PHP 8.1 syntax: declare(strict_types=1), parameter and return types.
A one-line comment above every method saying what it does.
At the end write the lines I should add to the $models array in index.php.

[PASTE THE CONTENTS OF THE FOUR SKELETON FILES AND SCHEMA.SQL HERE]

Why the prompt is written this way:

  • You attach the skeleton, not a description of it: the AI sees the exact namespace, method names and style, and the result fits the skeleton without changes.
  • “Add nothing else” for lookup tables stops the AI from writing its own getAll() into a five-line class, which would make inheritance pointless.
  • The class naming rule is there because the file name must match the class name, otherwise the PSR-4 autoloader will not find the file.
  • PHP 8.1 is stated explicitly because the AI otherwise likes newer constructs that do not run on sigma.tuke.sk.
  • The $models lines at the end save typos in the full class names.

Úlohy na cvičenieLab tasks

Úlohy dostaneš aj ako zadanie cv02 v Classroom 50, sú v súbore README.md v tvojom repository. Repository má na začiatku len README.md; kostru doň pridáš v úlohe 3.2.

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

Úloha 3.1: Kubeflow: príprava. Podľa návodu 04 Odovzdávanie, časť 1: otvor Kubeflow, skontroluj, že v Explorer je hore WEB, a skontroluj rozšírenia. Ak dole na stavovej lište nie je Go Live, rozšírenia sa po reštarte stratili. Vráti ich tento príkaz v termináli (jeden riadok):

code-server --install-extension Natizyskunk.sftp --install-extension yandeu.five-server --install-extension bmewburn.vscode-intelephense-client --install-extension mblode.twig-language-2

Potom F1, napíš reload, Developer: Reload Window.

Úloha 3.2: Clone, kostra a nastavenie. Prijmi zadanie cv02 (link je vyššie) a repository naklonuj do ~/web/it/cv02 podľa návodu 04 Odovzdávanie, časti 2 a 3 (posledné slovo príkazu je cv02). Repository má zatiaľ len README.md; kostru stiahneš z webu predmetu a rozbalíš do neho. V termináli:

cd ~/web/it/cv02
curl -O https://beata.stehlikova.website.tuke.sk/it/kostra.zip
unzip kostra.zip && rm kostra.zip
composer install
cp config.example.php config.php

V Explorer sa objavia súbory kostry (.htaccess a .gitignore začínajú bodkou, Explorer ich ukáže sivšie). Otvor config.php v editore a doplň dbname, user a pass (heslo z cvičenia). Ulož. Potom pravý klik na priečinok cv02, Upload Folder – tým sa na sigma.tuke.sk dostane aj vendor/, ktorý neprešiel editorom. Kontrola: https://sigma.tuke.sk/student/meno.priezvisko/it/cv02/ ukáže stránku „Kontrola projektu” s 0 tabuľkami.

Úloha 3.3: Tabuľky a testovacie dáta cez AI. Prompt z Ukážky 7 vlož do AI spolu s dátovým modelom zo svojho README z cv01. Výsledok ulož ako sql/schema.sql a sql/seed.sql. Prečítaj si každý ON DELETE, musí sedieť s tvojím modelom. V Adminer klikni vľavo SQL command, vlož obsah schema.sql, Execute; to isté so seed.sql. Kontrola: v Adminer vidíš svoje tabuľky s dátami a stránka „Kontrola projektu” ich vypíše v zozname.

Úloha 3.4: Modely cez AI. Prompt z Ukážky 8 vlož do AI spolu so súbormi src/Model/ModelInterface.php, BaseModel.php, LookupModel.php, MainModel.php a svojím sql/schema.sql. Vzniknuté triedy ulož do src/Model/ (jedna trieda = jeden súbor, názov súboru = názov triedy). Vzorové LookupModel.php a MainModel.php potom zmaž. Prečítaj každú metódu, pri obhajobe ju vysvetlíš.

Úloha 3.5: Kontrolná stránka. V index.php doplň do poľa $models jeden riadok new \App\Model\TvojModel(), pre každú svoju triedu. Ulož a otvor stránku na sigma.tuke.sk: pri každom modeli vidíš popis, počet záznamov a prvých 5 riadkov. Pri hlavnej entite musí byť aj stĺpec s názvom z číselníka (JOIN). Ak stránka hlási chybu, prečítaj ju – debug v config.php je zapnutý práve preto.

Úloha 3.6: Odovzdanie. Commit a push podľa návodu 04 Odovzdávanie, časť 5. config.php a vendor/ do repository nejdú (sú v .gitignore), to je správne. Na GitHub skontroluj, že je tam celá kostra, sql/, src/Model/ s tvojimi triedami a index.php.

Úloha 3.7: Kontrola na sigma.tuke.sk. Pravý klik na cv02, Upload Folder, potom otvor https://sigma.tuke.sk/student/meno.priezvisko/it/cv02/. Over aj, že …/it/cv02/src/ a …/it/cv02/config.php vrátia chybu 404 alebo 403 – kód a heslo nie sú z webu prístupné.

Hodnotenie: 1 bod. Vlastné tabuľky s testovacími dátami v databáze, modely v repository a kontrolná stránka vo webovom priestore na sigma.tuke.sk, ktorá vypíše záznamy z každej tabuľky. Commit a push najneskôr do nasledujúceho cvičenia.

You also get the tasks as the assignment cv02 in Classroom 50; they are in the file README.md in your repository. The repository has only README.md at first; you add the skeleton in task 3.2.

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

Task 3.1: Kubeflow: getting ready. Following guide 04 Submitting, part 1: open Kubeflow, check that Explorer shows WEB at the top, and check the extensions. If the status bar at the bottom does not show Go Live, the extensions were lost on restart. This command in the terminal (one line) brings them back:

code-server --install-extension Natizyskunk.sftp --install-extension yandeu.five-server --install-extension bmewburn.vscode-intelephense-client --install-extension mblode.twig-language-2

Then F1, type reload, Developer: Reload Window.

Task 3.2: Clone, skeleton and setup. Accept the assignment cv02 (link above) and clone the repository into ~/web/it/cv02 following guide 04 Submitting, parts 2 and 3 (the last word of the command is cv02). The repository has only README.md so far; you download the skeleton from the course website and unpack it into the repository. In the terminal:

cd ~/web/it/cv02
curl -O https://beata.stehlikova.website.tuke.sk/it/kostra.zip
unzip kostra.zip && rm kostra.zip
composer install
cp config.example.php config.php

The skeleton files appear in Explorer (.htaccess and .gitignore start with a dot; Explorer shows them greyed). Open config.php in the editor and fill in dbname, user and pass (the password from the lab). Save. Then right-click the cv02 folder, Upload Folder – this gets vendor/, which did not pass through the editor, to sigma.tuke.sk as well. Check: https://sigma.tuke.sk/student/name.surname/it/cv02/ shows the “Kontrola projektu” page with 0 tables.

Task 3.3: Tables and test data with AI. Paste the prompt from Example 7 into an AI together with the data model from your cv01 README. Save the result as sql/schema.sql and sql/seed.sql. Read every ON DELETE; it must match your model. In Adminer click SQL command on the left, paste the contents of schema.sql, Execute; the same with seed.sql. Check: Adminer shows your tables with data and the “Kontrola projektu” page lists them.

Task 3.4: Models with AI. Paste the prompt from Example 8 into an AI together with the files src/Model/ModelInterface.php, BaseModel.php, LookupModel.php, MainModel.php and your sql/schema.sql. Save the generated classes into src/Model/ (one class = one file, file name = class name). Then delete the example LookupModel.php and MainModel.php. Read every method; you will explain it at the defence.

Task 3.5: Check page. In index.php add one line new \App\Model\YourModel(), to the $models array for each of your classes. Save and open the page on sigma.tuke.sk: for every model you see the description, the record count and the first 5 rows. The main entity must also show the column with the name from the lookup table (JOIN). If the page reports an error, read it – debug in config.php is on exactly for this.

Task 3.6: Submitting. Commit and push following guide 04 Submitting, part 5. config.php and vendor/ do not go into the repository (they are in .gitignore); that is correct. On GitHub check that the whole skeleton, sql/, src/Model/ with your classes and index.php are there.

Task 3.7: Check on sigma.tuke.sk. Right-click cv02, Upload Folder, then open https://sigma.tuke.sk/student/name.surname/it/cv02/. Also check that …/it/cv02/src/ and …/it/cv02/config.php return a 404 or 403 error – the code and the password are not reachable from the web.

Grading: 1 point. Your own tables with test data in the database, models in the repository and the check page in your web space on sigma.tuke.sk listing the records of every table. 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. Prvý míľnik (4. týždeň) pokrýva týždne 2–4: dostaneš jednu položku z „Vysvetli”, jednu z „Uprav” a jednu zo „Zdôvodni”, spolu cca 5 minút.

Pred obhajobou si aktuálny stav projektu skopíruješ do samostatného priečinka, aby odovzdané zadanie ostalo nedotknuté. V termináli v Kubeflow:

cd ~/web/it
mkdir obhajoba1
cp -r cv03/. obhajoba1/
rm -rf obhajoba1/.git

Potom pravý klik na obhajoba1 → Upload Folder. Live coding sa robí v obhajoba1; uloženie v editore ide na sigma.tuke.sk samo. 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 robí composer install a čo je v priečinku vendor/.
  2. Prečo vendor/ a config.php nie sú v repository a ako sa dostanú na sigma.tuke.sk.
  3. Čo znamená riadok "App\\": "src/" v composer.json.
  4. Podľa plného mena triedy (napr. App\Model\CategoryModel) povedať cestu k súboru a naopak.
  5. Čo robí riadok namespace App\Model; a čo riadok use App\Database;.
  6. Prečo je v celej aplikácii jediný require a kde je.
  7. Čo je v config.php a čo robí riadok $c = require __DIR__ . '/../config.php';.
  8. Čo je DSN a z čoho sa skladá.
  9. Čo robí Database::getInstance() pri prvom a pri druhom volaní; prečo je konštruktor private.
  10. Prečo je $table v BaseModel protected a nie private.
  11. Prečo je BaseModel abstract a čo musí potomok napísať.
  12. Čo robí fetchColumn() v getCount() a prečo je tam (int).
  13. Čo vráti fetch(), keď záznam neexistuje, a ako to getById() prevedie na null.
  14. Rozdiel medzi query() a prepare() + execute(); kedy ktorý.
  15. Čo robí JOIN … ON v getAll() hlavnej entity a čo by bolo vo výsledku bez neho.
  16. Prečo hlavná entita nededí z BaseModel.
  17. Ako index.php vie zavolať describe() na každom modeli bez ohľadu na jeho triedu (interface).
  18. Poradie príkazov v schema.sql – prečo DROP naopak ako CREATE.
  19. Čo urobí databáza pri delete() záznamu, ktorý používa iná tabuľka s RESTRICT.
  20. Čo robí .htaccess v kostre a ako si overíš, že funguje.

Uprav (live coding)

Zmeny v kóde vidno na kontrolnej stránke; SQL sa spúšťa v Adminer → SQL command. Nič z toho trvalo nemení dáta.

  1. Zmeň poradie záznamov hlavnej entity na abecedné podľa názvu.
  2. Vypíš v kontrolnej stránke len prvé 3 riadky každého modelu namiesto 5.
  3. Doplň do describe() číselníka počet záznamov, napr. „Číselník kategórií (4)“.
  4. Pridaj do číselníkového modelu metódu getByName(string $name): ?array a zavolaj ju v index.php.
  5. Pridaj do getAll() hlavnej entity ďalší stĺpec z číselníka pod vlastným aliasom.
  6. Uprav getCount() hlavnej entity tak, aby počítal len záznamy s danou hodnotou cudzieho kľúča (WHERE).
  7. Vypíš v index.php modely v opačnom poradí alebo len tie, ktoré majú viac ako 3 záznamy.
  8. Napíš bez AI nový model pre jeden svoj číselník, ktorý zatiaľ model nemá, a pridaj ho do $models.
  9. V Adminer napíš SELECT, ktorý vráti záznamy hlavnej entity s názvom z číselníka, zoradené podľa iného stĺpca než id.
  10. V Adminer napíš SELECT s COUNT(*) a GROUP BY, ktorý vráti počet záznamov hlavnej entity pre každú hodnotu číselníka.

Zdôvodni (design decisions)

  1. Prečo hlavná entita nededí z BaseModel, keď číselníky dedia.
  2. Prečo je Database singleton a nie obyčajná trieda, ktorú si každý model vytvorí sám.
  3. Prečo je config.php mimo repository, keď kód aj tak nikto cudzí nevidí.
  4. Prečo je hláška 1451 pri RESTRICT správne správanie a nie chyba programu.
  5. Prečo vendor/ ide na sigma.tuke.sk cez Upload Folder a na GitHub nie.
  6. Prečo sú src/, sql/ a vendor/ tri rôzne priečinky a čo by sa stalo, keby bolo všetko v jednom.

Definition of Done

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

  • sql/schema.sql a sql/seed.sql sú v repository a po spustení v Adminer vidíš svoje tabuľky s dátami,
  • v src/Model/ je model pre každú svoju tabuľku (okrem prepojok), vzorové LookupModel.php a MainModel.php sú zmazané,
  • kontrolná stránka vo webovom priestore na sigma.tuke.sk vypíše všetky tabuľky a pri každom modeli dáta, pri hlavnej entite aj stĺpec z číselníka,
  • …/cv02/src/ vráti 404,
  • commit a push sú na GitHub, vendor/ ani config.php v repository nie sú.

At the defence only the published questions and tasks are used. The first milestone (week 4) covers weeks 2–4: you get one item from “Explain”, one from “Modify” and one from “Justify”, about 5 minutes in total.

Before the defence you copy the current state of your project into a separate folder, so that the submitted assignment stays untouched. In the Kubeflow terminal:

cd ~/web/it
mkdir obhajoba1
cp -r cv03/. obhajoba1/
rm -rf obhajoba1/.git

Then right-click obhajoba1 → Upload Folder. Live coding is done in obhajoba1; a save in the editor goes to sigma.tuke.sk by itself. The repository and GitHub are not changed. The “Modify” tasks are also extension tasks for fast students: whoever tries them in advance has an easier defence.

Explain (code walkthrough)

Over your project you can say:

  1. What composer install does and what is in the vendor/ folder.
  2. Why vendor/ and config.php are not in the repository and how they get to sigma.tuke.sk.
  3. What the line "App\\": "src/" in composer.json means.
  4. From a full class name (e.g. App\Model\CategoryModel) give the file path and vice versa.
  5. What the line namespace App\Model; does and what use App\Database; does.
  6. Why there is a single require in the whole application and where it is.
  7. What is in config.php and what the line $c = require __DIR__ . '/../config.php'; does.
  8. What a DSN is and what it consists of.
  9. What Database::getInstance() does on the first and on the second call; why the constructor is private.
  10. Why $table in BaseModel is protected and not private.
  11. Why BaseModel is abstract and what a child must write.
  12. What fetchColumn() does in getCount() and why (int) is there.
  13. What fetch() returns when the record does not exist and how getById() turns it into null.
  14. The difference between query() and prepare() + execute(); when to use which.
  15. What JOIN … ON does in the main entity’s getAll() and what the result would hold without it.
  16. Why the main entity does not inherit from BaseModel.
  17. How index.php can call describe() on every model regardless of its class (interface).
  18. The order of statements in schema.sql – why DROP is reversed compared to CREATE.
  19. What the database does on delete() of a record used by another table with RESTRICT.
  20. What .htaccess in the skeleton does and how you check that it works.

Modify (live coding)

Code changes are visible on the check page; SQL is run in Adminer → SQL command. None of this changes data permanently.

  1. Change the order of the main entity’s records to alphabetical by name.
  2. Show only the first 3 rows of each model on the check page instead of 5.
  3. Add the record count to a lookup model’s describe(), e.g. “Categories (4)”.
  4. Add a method getByName(string $name): ?array to a lookup model and call it in index.php.
  5. Add another lookup-table column to the main entity’s getAll() under your own alias.
  6. Change the main entity’s getCount() to count only records with a given foreign-key value (WHERE).
  7. List the models in index.php in reverse order, or only those with more than 3 records.
  8. Without AI, write a new model for one of your lookup tables that has none yet and add it to $models.
  9. In Adminer write a SELECT that returns the main entity’s records with the lookup name, ordered by a column other than id.
  10. In Adminer write a SELECT with COUNT(*) and GROUP BY that returns the number of main-entity records for each lookup value.

Justify (design decisions)

  1. Why the main entity does not inherit from BaseModel while lookup models do.
  2. Why Database is a singleton and not an ordinary class each model creates for itself.
  3. Why config.php is outside the repository when nobody else sees the code anyway.
  4. Why message 1451 with RESTRICT is correct behaviour and not a program error.
  5. Why vendor/ goes to sigma.tuke.sk with Upload Folder and not to GitHub.
  6. Why src/, sql/ and vendor/ are three different folders and what would happen if everything were in one.

Definition of Done

The week is done when:

  • sql/schema.sql and sql/seed.sql are in the repository and after running them in Adminer you see your tables with data,
  • src/Model/ has a model for each of your tables (except pivot tables), the example LookupModel.php and MainModel.php are deleted,
  • the check page in your web space on sigma.tuke.sk lists all tables and data for every model, with the lookup column for the main entity,
  • …/cv02/src/ returns 404,
  • commit and push are on GitHub, neither vendor/ nor config.php is in the repository.