Návod

Databáza

Použitie `Database`, QueryBuildera a transakcií.

Odovzdaj Database do služby

Controller nechaj riešiť HTTP a persistenciu presuň do repository alebo aplikačnej služby. Závislosť Database odovzdaj cez konštruktor tam, kam databázová práca skutočne patrí.

example.php
<?php

declare(strict_types=1);

namespace App\Services;

use Lemonade\Framework\Database\Database;

final class ArticleRepository
{
    public function __construct(
        private readonly Database $db,
    ) {}
}

Používaj QueryBuilder na čítanie aj zápis

Pre bežné CRUD dotazy je dobrým východiskovým bodom table(). V dokumentácii používaj neutrálnu tabuľku articles a stĺpce id, title a published.

example.php
$articles = $this->db->table('articles')
    ->select(['id', 'title', 'published'])
    ->where('published', 1)
    ->orderBy('id', 'DESC')
    ->getArray();

Súvisiace zápisy obaľ do transakcie

Viackrokové zápisy obaľ do Database::transaction(), aby súvisiace zmeny buď uspeli všetky, alebo sa všetky vrátili späť.

example.php
$this->db->transaction(function (): void {
    $this->db->table('articles')->insert([
        'title' => 'New article',
        'published' => 1,
    ]);

    $this->db->table('article_audit')->insert([
        'event' => 'created',
    ]);
});