Guide

Database

Using `Database`, QueryBuilder, and transactions.

Inject Database into the service

Let the controller handle HTTP and move persistence into a repository or application service. Inject Database through the constructor where database work actually belongs.

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,
    ) {}
}

Use QueryBuilder for reads and writes

For common CRUD queries, table() is a good starting point. Documentation examples use the neutral articles table with id, title, and published columns.

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

Wrap related writes in a transaction

Wrap multi-step writes in Database::transaction() so related changes either all succeed or are all rolled back.

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',
    ]);
});