Database design: keys, relationships and normalization
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
Group data and behaviour together, and use a class to wrap database work.
<?php
class User
{
public function __construct(
public string $name,
private string $email
) {}
public function email(): string
{
return $this->email;
}
public function greeting(): string
{
return 'Hello ' . $this->name;
}
}
$u = new User('Ali', 'ali@example.com');
echo $u->greeting();public: usable from anywhere.private: only inside the class.protected: inside the class and its children.class Str
{
public static function slug(string $s): string
{
return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($s)), '-');
}
}
echo Str::slug('Hello World!'); // hello-worldclass UserRepo
{
public function __construct(private PDO $pdo) {}
public function find(int $id): ?array
{
$s = $this->pdo->prepare('SELECT * FROM users WHERE id = ?');
$s->execute([$id]);
return $s->fetch() ?: null;
}
}All the SQL for users now lives in one place, which makes changes and testing easier.
Start small. Use classes where they remove repetition, not everywhere.
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
A folder layout and a few habits that keep a growing PHP site tidy, secure and easy to maintain.