Repository navigation
Expand file tree
/
Copy pathFindProductByIdQuery.php
More file actions
50 lines (43 loc) · 1.97 KB
/
Copy pathFindProductByIdQuery.php
File metadata and controls
50 lines (43 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
declare(strict_types=1);
namespace App\Product;
use SqlFirstDemo\Db\DbServiceInterface;
/**
* A QUERY CLASS: one class, one SQL statement, one job.
*
* The shape every query class in the application follows:
*
* - `final readonly`, no base class, no state beyond the injected gateway.
* - The SQL is a `public const string SQL`. Public so a unit test can configure the fake with
* the exact text, and so the prepare check can find every statement in the codebase by
* reflection (`tests/Support/SqlConstantFinder.php`) and have MySQL validate it.
* - The SQL is written out in full, as SQL. Not assembled. What you read in this file is what
* the server receives, which is also what you paste into a MySQL client to EXPLAIN it.
* - Parameters are named (`:id`) and bound, never interpolated.
* - One public method, named for what it does, taking typed arguments and returning a typed
* result (here `?Product`: null means "no such product").
*
* Callers construct it where they need it: `new FindProductByIdQuery($db)->execute($id)`. In a
* framework app you would exclude query classes from autowiring and inject only the
* {@see DbServiceInterface}; query objects are cheap to build and have no dependencies worth
* managing.
*
* The column list is spelled out rather than `SELECT *`, so adding a column to the table never
* changes what this query returns, and a column dropped from the table fails the prepare check.
*/
final readonly class FindProductByIdQuery
{
public const string SQL = <<<'SQL'
SELECT id, sku, name, description, status, unit_price, sale_price, stock, supplier_id, is_featured
FROM product
WHERE id = :id
SQL;
public function __construct(private DbServiceInterface $db)
{
}
public function execute(int $id): ?Product
{
$row = $this->db->queryRows(self::SQL, [ProductTable::COL_ID => $id])->firstOrNull();
return null === $row ? null : Product::fromRow($row);
}
}