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)
.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:
- Rozbalíš
kostra.zipdo~/web/it/cv02v Kubeflow. - V termináli v
cv02spustíšcomposer install. Vznikne priečinokvendor/(časť 2). - Skopíruješ
config.example.phpnaconfig.phpa doplníš prihlasovacie údaje k databáze (časť 5). - Pravým tlačidlom na
cv02→ Upload Folder. Celý priečinok sa skopíruje na sigma.tuke.sk. - Necháš si od AI vyrobiť
sql/schema.sqlasql/seed.sqlzo svojho README a spustíš ich v Adminer (časť 6). - Necháš si od AI vyrobiť modely pre svoje tabuľky podľa vzorov v kostre a pridáš ich do
index.php(časť 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.phpnačítavendor/autoload.php. Priečinok skopíruješ ručne: v Explorer klikni pravým tlačidlom nacv02→ 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
.gitignoreje riadokvendor/, takžegit addho preskočí. Kto stiahne repository, spustícomposer installa 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:
<?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
];
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;rje skratka (alias) tabuľky.JOIN difficulties d ON d.id = r.difficulty_id– ku každému receptu pripoj obtiažnosť, ktorejidsa rovnádifficulty_idreceptu. ZaONje vždy „primárny kľúč jednej tabuľky = cudzí kľúč druhej”.d.name AS difficulty_name– stĺpecnamez obtiažnosti pod iným menom, aby sa v PHP neplietol s inýmname. 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):
<?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}";
}
}
<?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:
<?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)
.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:
- Unpack
kostra.zipinto~/web/it/cv02in Kubeflow. - In the terminal in
cv02runcomposer install. The foldervendor/is created (section 2). - Copy
config.example.phptoconfig.phpand fill in the database login details (section 5). - Right-click
cv02→ Upload Folder. The whole folder is copied to sigma.tuke.sk. - Let the AI create
sql/schema.sqlandsql/seed.sqlfrom your README and run them in Adminer (section 6). - Let the AI create models for your tables following the examples in the skeleton and add them to
index.php(section 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.phploadsvendor/autoload.php. You copy the folder by hand: in Explorer right-clickcv02→ 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.
.gitignorehas the linevendor/, sogit addskips it. Whoever downloads the repository runscomposer installand 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:
<?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
];
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;ris a table alias.JOIN difficulties d ON d.id = r.difficulty_id– to every recipe attach the difficulty whoseidequals the recipe’sdifficulty_id. AfterONthere is always “primary key of one table = foreign key of the other”.d.name AS difficulty_name– the columnnamefrom the difficulty under another name, so that it is not confused with anothernamein 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):
<?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}";
}
}
<?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:
<?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
{
"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
<?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 jeApp\Database, súbor jesrc/Database.php.use PDO;– PDO je zabudovaná trieda PHP bez namespace; keďže my sme v namespaceApp, 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 alebonull; na začiatkunull, 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 jeconfig.php.requiretu vráti pole zreturn.new PDO($dsn, $c['user'], $c['pass'], [...])– samotné pripojenie. Tretí a štvrtý parameter sú používateľ a heslo zconfig.php.ATTR_ERRMODE => ERRMODE_EXCEPTION– chyba v SQL vyhodí výnimku (PDOException), ktorú vidíš v prehliadači, keď jedebugzapnutý; 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
<?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;
}
<?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 alebofalse, keď nič nenašiel. Pretoreturn $row === false ? null : $row;– metóda sľubuje?array, teda pole alebonull, niefalse.getCount():fetchColumn()vráti prvý stĺpec prvého riadka – priCOUNT(*)priamo číslo;(int)ho prevedie z reťazca na celé číslo, lebo metóda sľubujeint.delete(): poexecute()povierowCount(), koľko riadkov sa zmazalo;> 0dátrue/false. Ak záznam používa iná tabuľka sON 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.
-- 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ú:
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.)
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.
schema.sql je v ľavom paneli 7 tabuliek, všetky InnoDB a utf8mb4_unicode_ci.
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í“.
recipe_id a ingredient_id, tri cudzie kľúče – na recept CASCADE, na surovinu a jednotku RESTRICT. Presne podľa README.
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.
<?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í';
}
}
<?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,$pdoa š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 akoBaseModel.SELECT r.*, d.name AS difficulty_name FROM recipes r JOIN difficulties d ON d.id = r.difficulty_id–radsú 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 … ONspojí riadok receptu s riadkom obtiažnosti, ktorý má rovnakéidakodifficulty_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ýmJOINaWHERE r.id = :id– pri aliasoch treba povedať, ktorej tabuľkyidmyslíme.getCount()adelete()sú rovnaké ako vBaseModel, 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ýrequirev aplikácii; od tohto riadka PHP nájde každú trieduApp\…samo.$config = require __DIR__ . '/config.php';aif ($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áciidebugnatrue.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, žeindex.phpnie je v žiadnom namespace ausesme použili len preDatabase.foreach ($models as $model)– pre každý modeldescribe(),getCount()a prvých päť riadkov zgetAll()cezarray_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).
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
# 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:
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.sqlpotom padne na cudzom kľúči. ENGINE,CHARSETa 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 DATABASEaUSEzakazujeme, 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
$modelsna konci ušetria preklepy v plných menách tried.
Example 1: 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
<?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 isApp\Database, the file issrc/Database.php.use PDO;– PDO is a built-in PHP class without a namespace; since we are inside the namespaceApp, 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 ornull;nullat 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, whereconfig.phpis.requirehere returns the array fromreturn.new PDO($dsn, $c['user'], $c['pass'], [...])– the connection itself. The third and fourth parameters are the user and the password fromconfig.php.ATTR_ERRMODE => ERRMODE_EXCEPTION– an SQL error throws an exception (PDOException), which you see in the browser whendebugis 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
<?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;
}
<?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;protectedso 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 orfalsewhen nothing was found. Hencereturn $row === false ? null : $row;– the method promises?array, i.e. an array ornull, notfalse.getCount():fetchColumn()returns the first column of the first row – withCOUNT(*)that is the number itself;(int)converts it from a string to an integer, because the method promisesint.delete(): afterexecute(),rowCount()says how many rows were deleted;> 0givestrue/false. If another table uses the record withON 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.
-- 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:
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.)
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.
schema.sql the left panel shows 7 tables, all InnoDB and utf8mb4_unicode_ci.
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”.
recipe_id and ingredient_id, three foreign keys – CASCADE to the recipe, RESTRICT to the ingredient and the unit. Exactly as in the README.
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.
<?php
declare(strict_types=1);
namespace App\Model;
class DifficultyModel extends BaseModel
{
protected string $table = 'difficulties';
public function describe(): string
{
return 'Difficulty lookup table';
}
}
<?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,$pdoand 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 ownprivate PDO $pdo;(it may beprivatehere, nobody inherits from it) and its own constructor, which asks for the connection just likeBaseModel.SELECT r.*, d.name AS difficulty_name FROM recipes r JOIN difficulties d ON d.id = r.difficulty_id–randdare table aliases.r.*= all columns of the recipe,d.name AS difficulty_name= plus the difficulty name under a readable name.JOIN … ONpairs the recipe row with the difficulty row whoseidequalsdifficulty_id. In the result$row['difficulty_name']is “medium” instead of the number 2.ORDER BY r.id DESC– newest recipes first; lookup tables useORDER BY id, because insertion order is also display order.getById()with the sameJOINandWHERE r.id = :id– with aliases you must say which table’sidyou mean.getCount()anddelete()are the same as inBaseModel, 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 onlyrequirein the application; from this line on PHP finds every classApp\…by itself.$config = require __DIR__ . '/config.php';andif ($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 whendebugistruein 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\becauseindex.phpis in no namespace and we useduseonly forDatabase.foreach ($models as $model)– for every modeldescribe(),getCount()and the first five rows ofgetAll()viaarray_slice. The table header comes fromarray_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).
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
# 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:
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.sqlthen fails on a foreign key. ENGINE,CHARSETand 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 DATABASEandUSEare 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
$modelslines 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ť:
- Čo robí
composer installa čo je v priečinkuvendor/. - Prečo
vendor/aconfig.phpnie sú v repository a ako sa dostanú na sigma.tuke.sk. - Čo znamená riadok
"App\\": "src/"vcomposer.json. - Podľa plného mena triedy (napr.
App\Model\CategoryModel) povedať cestu k súboru a naopak. - Čo robí riadok
namespace App\Model;a čo riadokuse App\Database;. - Prečo je v celej aplikácii jediný
requirea kde je. - Čo je v
config.phpa čo robí riadok$c = require __DIR__ . '/../config.php';. - Čo je DSN a z čoho sa skladá.
- Čo robí
Database::getInstance()pri prvom a pri druhom volaní; prečo je konštruktorprivate. - Prečo je
$tablevBaseModelprotecteda nieprivate. - Prečo je
BaseModelabstracta čo musí potomok napísať. - Čo robí
fetchColumn()vgetCount()a prečo je tam(int). - Čo vráti
fetch(), keď záznam neexistuje, a ako togetById()prevedie nanull. - Rozdiel medzi
query()aprepare()+execute(); kedy ktorý. - Čo robí
JOIN … ONvgetAll()hlavnej entity a čo by bolo vo výsledku bez neho. - Prečo hlavná entita nededí z
BaseModel. - Ako
index.phpvie zavolaťdescribe()na každom modeli bez ohľadu na jeho triedu (interface). - Poradie príkazov v
schema.sql– prečoDROPnaopak akoCREATE. - Čo urobí databáza pri
delete()záznamu, ktorý používa iná tabuľka s RESTRICT. - Čo robí
.htaccessv 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.
- Zmeň poradie záznamov hlavnej entity na abecedné podľa názvu.
- Vypíš v kontrolnej stránke len prvé 3 riadky každého modelu namiesto 5.
- Doplň do
describe()číselníka počet záznamov, napr. „Číselník kategórií (4)“. - Pridaj do číselníkového modelu metódu
getByName(string $name): ?arraya zavolaj ju vindex.php. - Pridaj do
getAll()hlavnej entity ďalší stĺpec z číselníka pod vlastným aliasom. - Uprav
getCount()hlavnej entity tak, aby počítal len záznamy s danou hodnotou cudzieho kľúča (WHERE). - Vypíš v
index.phpmodely v opačnom poradí alebo len tie, ktoré majú viac ako 3 záznamy. - Napíš bez AI nový model pre jeden svoj číselník, ktorý zatiaľ model nemá, a pridaj ho do
$models. - 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. - V Adminer napíš
SELECTsCOUNT(*)aGROUP BY, ktorý vráti počet záznamov hlavnej entity pre každú hodnotu číselníka.
Zdôvodni (design decisions)
- Prečo hlavná entita nededí z
BaseModel, keď číselníky dedia. - Prečo je
Databasesingleton a nie obyčajná trieda, ktorú si každý model vytvorí sám. - Prečo je
config.phpmimo repository, keď kód aj tak nikto cudzí nevidí. - Prečo je hláška 1451 pri RESTRICT správne správanie a nie chyba programu.
- Prečo
vendor/ide na sigma.tuke.sk cez Upload Folder a na GitHub nie. - Prečo sú
src/,sql/avendor/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.sqlasql/seed.sqlsú 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.phpaMainModel.phpsú 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/aniconfig.phpv 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:
- What
composer installdoes and what is in thevendor/folder. - Why
vendor/andconfig.phpare not in the repository and how they get to sigma.tuke.sk. - What the line
"App\\": "src/"incomposer.jsonmeans. - From a full class name (e.g.
App\Model\CategoryModel) give the file path and vice versa. - What the line
namespace App\Model;does and whatuse App\Database;does. - Why there is a single
requirein the whole application and where it is. - What is in
config.phpand what the line$c = require __DIR__ . '/../config.php';does. - What a DSN is and what it consists of.
- What
Database::getInstance()does on the first and on the second call; why the constructor isprivate. - Why
$tableinBaseModelisprotectedand notprivate. - Why
BaseModelisabstractand what a child must write. - What
fetchColumn()does ingetCount()and why(int)is there. - What
fetch()returns when the record does not exist and howgetById()turns it intonull. - The difference between
query()andprepare()+execute(); when to use which. - What
JOIN … ONdoes in the main entity’sgetAll()and what the result would hold without it. - Why the main entity does not inherit from
BaseModel. - How
index.phpcan calldescribe()on every model regardless of its class (interface). - The order of statements in
schema.sql– whyDROPis reversed compared toCREATE. - What the database does on
delete()of a record used by another table with RESTRICT. - What
.htaccessin 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.
- Change the order of the main entity’s records to alphabetical by name.
- Show only the first 3 rows of each model on the check page instead of 5.
- Add the record count to a lookup model’s
describe(), e.g. “Categories (4)”. - Add a method
getByName(string $name): ?arrayto a lookup model and call it inindex.php. - Add another lookup-table column to the main entity’s
getAll()under your own alias. - Change the main entity’s
getCount()to count only records with a given foreign-key value (WHERE). - List the models in
index.phpin reverse order, or only those with more than 3 records. - Without AI, write a new model for one of your lookup tables that has none yet and add it to
$models. - In Adminer write a
SELECTthat returns the main entity’s records with the lookup name, ordered by a column other thanid. - In Adminer write a
SELECTwithCOUNT(*)andGROUP BYthat returns the number of main-entity records for each lookup value.
Justify (design decisions)
- Why the main entity does not inherit from
BaseModelwhile lookup models do. - Why
Databaseis a singleton and not an ordinary class each model creates for itself. - Why
config.phpis outside the repository when nobody else sees the code anyway. - Why message 1451 with RESTRICT is correct behaviour and not a program error.
- Why
vendor/goes to sigma.tuke.sk with Upload Folder and not to GitHub. - Why
src/,sql/andvendor/are three different folders and what would happen if everything were in one.
Definition of Done
The week is done when:
sql/schema.sqlandsql/seed.sqlare 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 exampleLookupModel.phpandMainModel.phpare 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/norconfig.phpis in the repository.