# Entities and a database
Entities, mmo.pdo on SQLite, the repository, queries, commits and patches.
- **You will have:** the team of **Your first controller** in a SQLite table: listed and filtered by the database,
one member by its id, a new member added by a `POST`, a wrong one refused with nothing written, and their tests.
- **You need:** **Your first controller** done.
## 1. Add mmo.pdo
mmo.pdo puts SQLite and MySQL behind the framework's entities. Add it to the project's dependencies, in `mmo.json`:
```json from=mmo.json
"dependencies": {
"mmo.core": "21.*",
"mmo.client": "4.*",
"mmo.pdo": "2.*"
},
```
The hub already has it in `libs/`: there is nothing to download.
## 2. The entity
A row of a table is an **entity**: a class whose properties marked `#[ArrayProperty]` are its columns. Create
`src/entities/Member.php`:
```php from=src/entities/Member.php
class Member extends PDOEntity {
/** the property that is its id */
const ID_PROP = 'id';
/** the roles a member may have */
const ROLES = ['engineering', 'sales', 'support'];
#[ArrayProperty()] protected int $id = 0;
#[ArrayProperty()] protected string $name = '';
#[ArrayProperty()] protected string $role = 'engineering';
public function getLabel(): string {return $this->name;}
```
It also says what a valid member is, so that a request is checked **before** anything is created:
```php from=src/entities/Member.php
static public function Check(array $data): array {
$errors = [];
if (trim((string)($data['name'] ?? '')) === '') {$errors['name'] = 'a name is required.';}
if (!in_array($data['role'] ?? 'engineering', self::ROLES, true)) {$errors['role'] = 'one of: ' . implode(', ', self::ROLES) . '.';}
return $errors;
}
```
## 3. The database, in the configuration
The connection and the tables are declared in `configs/config.json`, not built in code. A value written
`{"$": "SomeClass", ...}` is an object: the framework builds it the first time it is read, with the other keys as
its properties. `"#db"` is a reference to the `db` entry.
```json from=configs/config.json
"db": {
"$": "MMO\\pdo\\SqliteHandler",
"filename": "{root}/db/acme.sqlite"
},
//its tables, and the entity class of each
"repo": {
"$": "MMO\\pdo\\PDORepository",
"handler": {"$": "#db"},
"tables": {
"members": {
"id": "INTEGER PRIMARY KEY AUTOINCREMENT",
"name": "VARCHAR(100) NOT NULL",
"role": "VARCHAR(20) NOT NULL"
}
},
"entities": {
"members": "AcmePortal\\entities\\Member"
}
},
```
The **repository** is the database seen as the framework sees every storage: **collections** of entities (one per
table, named after it) that you query and commit to. The same code would work on mmo.mongodb's repository, or on a
JSON file.
The file goes in `db/`: the web server may write there, and the root `.htaccess` refuses every file outside
`www/`, so the database is never downloaded. Keep it out of git:
```bash
echo "db/*.sqlite" >> .gitignore
```
## 4. Connect once, create the tables once
Something has to open the connection and create the tables the database does not have yet. `install()` never runs
by itself: creating tables as a side effect of loading the site is how a production schema gets rebuilt by
surprise. A module does it, the first time the repository is asked for, in `src/Database.php`:
```php from=src/Database.php
public function repository(): PDORepository {
/** @var PDORepository $repository */
$repository = \MMO\get('repo');
if (!$this->ready) {
$repository->getHandler()->connect();
//CREATE TABLE for every table the database does not have yet
$repository->install();
$this->ready = true;
}
return $repository;
}
```
`\MMO\get('repo')` reads the configuration's `repo`, built into a `PDORepository` the first time.
Require the three classes in `src/bootstrap.php`, each after what it uses:
```php from=src/bootstrap.php
require(__DIR__ . '/entities/Member.php');
require(__DIR__ . '/Database.php');
require(__DIR__ . '/controllers/TeamController.php');
```
## 5. Read: queries
The controller of the previous guide now reads the `members` collection. A query takes filters, then a sort; the
database does the work:
```php from=src/controllers/TeamController.php
public function routeList(Route $route): array {
$filters = $route->has('role')? ['role' => (string)$route->get('role')] : [];
return $this->members()->query($filters, sort: ['name'])->getEntities();
}
```
`query()` returns a `Query`: iterate it with `foreach`, or get the list with `getEntities()`. `['-name']` sorts the
other way; a filter can be an operator, `['id' => ['$gte' => 10]]`. One member, by its id, which is always a string:
```php from=src/controllers/TeamController.php
$id = (string)$route->get('id');
$member = $this->members()->getById($id) ?? throw new e404($this, $route, 'no member [{id}].', ['id' => $id]);
```
## 6. Write: create, then commit
Adding a member is creating an entity in its collection, then **committing**: nothing is written before
`\MMO\commit()`, and one commit is one transaction.
```php from=src/controllers/TeamController.php
$input = array_intersect_key((array)$route->getRequestBody(), ['name' => true, 'role' => true]);
if ($errors = Member::Check($input)) {
$route->setResponse($route->getResponse()->withStatus(422));
return ['errors' => $errors];
}
$member = $this->members()->createEntity($input);
\MMO\commit(Database::Shared()->repository());
$route->setResponse($route->getResponse()->withStatus(201));
return ['member' => $member];
```
Three things in these lines:
- **Only the fields you expect** are taken from the request: anything else in it is ignored.
- **Checked before created**: a refused request leaves nothing behind, not even in memory.
- **The status is set on the response**: 201 for a member created, 422 for a request refused.
The new member's id is the database's once the commit has run.
## 7. Try it
```bash
php -S localhost:8000 -t www www/index.php
curl -X POST -d 'name=Grace Hopper&role=engineering' http://localhost:8000/team.json
```
```json
{"member": {"id": 1, "name": "Grace Hopper", "role": "engineering", "status": "active", "uid": "...", "metadata": {"title": "Grace Hopper", "label": "Grace Hopper"}}}
```
`db/acme.sqlite` now exists. Beside the columns, every entity carries `status`, `uid` and `metadata`: the
framework's own, the same for every kind of storage.
## 8. Test it, on a database of its own
The tests must never touch `db/acme.sqlite`. They replace the file with a database in memory before the first
request, so each run starts empty:
```php from=tests/unit/TestTeam.php
static public function setUpBeforeClass(): void {
//a database of the tests' own, in memory: built empty, gone when they end, never the one of db/
\MMO\config(['db' => ['filename' => ':memory:']]);
}
```
```php from=tests/unit/TestTeam.php
public function testAWrongMemberIsRefusedAndNothingIsWritten(): void {
$before = count($this->json('GET', 'team.json')[1]);
[$status, $data] = $this->json('POST', 'team.json', ['name' => '', 'role' => 'pirate']);
$this->assertSame(422, $status);
$this->assertSame(['name', 'role'], array_keys($data['errors']));
$this->assertCount($before, $this->json('GET', 'team.json')[1]);
}
```
```bash
phpunit
```
## 9. Changing the tables later
`install()` creates a table that does not exist; it never changes one that does. Once the project is deployed, a
change of a table is a **patch**: a file of `db/patches/`, named after the version that brings it, that mmo.admin
applies exactly once on each server when it deploys (`php scripts/admin.php migrate`). `db/patches/README.md`
explains how; **Deploy** comes back to it.
## Common mistakes
- **Forgetting `\MMO\commit()`.** The request answers with the member, and nothing is in the database.
- **`getById(3)`.** An id is a string: `getById('3')`.
- **`$collection->query(...)` used as an array.** It is a `Query`: `->getEntities()` for the list.
- **The tests on the real database.** Point `db` somewhere else before the first request, as above.
- **`db/acme.sqlite` committed.** Add it to `.gitignore` before the first `git add`.
## Going further
- Next: **Your first .jhs element**, which shows the team in a page, or **Tests and verify**.
- [Repository](https://www.mmoframework.fr/en/documentation/mmo.pdo/Repository.md): queries, identity, filters on
references, commits and backups.
- [Tables](https://www.mmoframework.fr/en/documentation/mmo.pdo/Tables.md) and
[Filters](https://www.mmoframework.fr/en/documentation/mmo.pdo/Filters.md): every column type, every operator.
- [Entities](https://www.mmoframework.fr/en/documentation/mmo.core/Entities.md): entities in mmo.core.