Files
camelia-orm/README.md
T
dgarcia 0e756e45c7
Tests / PHP 8.4 (push) Failing after 5m34s
refactor!: require PHP 8.4
Drop support for PHP 8.3 and lower. The package now declares >=8.4, and CI runs
only on 8.4.

- composer.json: require php >=8.4.
- mago.toml: php-version = "8.4", matching the minimum supported version.
- phpstan.neon: phpVersion 80400.
- Upgrade phpstan/phpstan to ^2.3: 1.x cannot parse `new Foo()->bar()`, which the
  8.4 formatter now emits.
- Fix the type errors PHPStan 2 reports: class-string<static> variance,
  optional array offsets in fromEnvironment, list vs array for PdoConnection::$lru,
  ReflectionClass<Model> docblocks, Repository made covariant in T, and a redundant
  null comparison in validateRelationPath.
- CI: single PHP 8.4 job using the php:8.4-cli container instead of setup-php,
  which failed with a TLS handshake timeout on the runner.

BREAKING CHANGE: PHP 8.4 is now required.
2026-11-15 10:58:11 -03:00

154 lines
4.6 KiB
Markdown

# camelia/orm
[![Latest Stable Version](https://img.shields.io/packagist/v/camelia/orm.svg)](https://packagist.org/packages/camelia/orm)
[![Total Downloads](https://img.shields.io/packagist/dt/camelia/orm.svg)](https://packagist.org/packages/camelia/orm)
[![License](https://img.shields.io/packagist/l/camelia/orm.svg)](https://packagist.org/packages/camelia/orm)
[![Tests](https://git.dr2gsistemas.duckdns.org/dr2gsistemas/camelia-orm/actions/workflows/tests.yml/badge.svg)](https://git.dr2gsistemas.duckdns.org/dr2gsistemas/camelia-orm/actions)
Lightweight attribute-mapped Active Record ORM for MariaDB/MySQL over PDO.
- **Package:** `camelia/orm` · **Namespace:** `Camelia\Orm`
- **PHP** `>=8.4`, extensions `pdo_mysql` and `mbstring`
- **Runtime dependencies:** `psr/log` (PSR-3, optional usage). `brick/math` is a suggestion for
`BigDecimal` properties.
The contract lives in [`especificaciones-orm.md`](especificaciones-orm.md); this file only shows usage.
The full developer guide, organised by task, is in [`docs/GUIA-PROGRAMADOR.md`](docs/GUIA-PROGRAMADOR.md).
## Install
```bash
composer require camelia/orm
```
## Bootstrap
```php
use Camelia\Orm\Orm;
$orm = Orm::fromArray([
'host' => '127.0.0.1',
'user' => 'app',
'password' => 'secret',
'database' => 'erp',
]);
// or from CAMELIA_DB_HOST, CAMELIA_DB_USER, CAMELIA_DB_NAME, CAMELIA_DB_PASS
$orm = Orm::fromEnv();
```
## Declare a model
```php
use Camelia\Orm\Attribute\{TableName, PrimaryKey, AutoIncrement, Guarded};
use Camelia\Orm\Model;
#[TableName('usuarios')]
final class Usuario extends Model
{
#[PrimaryKey, AutoIncrement]
public ?int $codigo = null;
public string $nombre = '';
#[Guarded]
public string $passwordHash = '';
}
```
`#[TableName]` and exactly one `#[PrimaryKey]` are mandatory. A model that violates the rules throws
`MetadataException` on first use instead of failing silently later.
## Read
```php
$repo = $orm->repository(Usuario::class);
$repo->find(['activo' => true], [['nombre', 'ASC']], limit: 20);
$repo->findFirst(['correo' => 'a@x']);
$repo->findByPk(5);
$repo->findByPkOrFail(5); // throws RecordNotFoundException
$repo->count(['activo' => true]);
$repo->page(['activo' => true], [], page: 2, perPage: 25);
```
Fluent queries are immutable:
```php
use Camelia\Orm\Query\{Cond, GroupCond};
$repo->query()
->where('activo', true)
->where('fecha', Cond::between('2024-01-01', '2024-12-31'))
->whereGroup(fn (GroupCond $g) => $g->or('correo', Cond::like('%@camelia.dev')))
->orderByDesc('fecha')
->with(['cliente.ciudad'])
->page(page: 1, perPage: 25);
```
## Write
```php
$repo->save($usuario); // INSERT or UPDATE, decided by the primary key
$repo->create(['nombre' => 'Ana']); // new + hydrate + insert
$repo->update($usuario); // always UPDATE, all writable columns
$repo->delete($usuario);
$repo->patch(5, ['nombre' => 'Bea']); // partial update by primary key
$repo->remove(5);
```
`update()` writes the whole row. There is no dirty tracking: use `patch()` for partial updates.
Writing a model hydrated through `select()` throws `PartialModelException`.
## Transactions
```php
$orm->transaction(function (Orm $orm) {
$orm->repository(Usuario::class)->save($usuario);
});
```
Nested calls use savepoints and the original exception is rethrown.
## Errors
Every read and write throws on failure. Silent degradation to `[]` is deliberately absent: it hides
connection failures as empty results. Catch `DatabaseException` (or `DuplicateKeyException`,
`ForeignKeyViolationException`, `LockTimeoutException`) where degradation is genuinely intended.
## Development
The toolchain is [Mago](https://mago.carthage.software) plus PHPUnit and PHPStan.
```bash
composer install
composer fmt # format with Mago
composer fmt:check # CI: formatting must be clean
composer lint # CI: Mago linter
composer analyze # CI: Mago analyzer
composer phpstan # CI: PHPStan level 8
composer test # CI: PHPUnit
composer check # runs the five gates above, in order
composer test:integration # requires CAMELIA_TEST_DSN
```
Configuration:
| File | Purpose |
|---|---|
| `mago.toml` | formatter, linter, analyzer |
| `mago-baseline.toml` | accepted analyzer findings (values coming from PDO) |
| `phpstan.neon` | level 8, `phpVersion: 80400` |
| `phpunit.xml.dist` | unit suite |
| `phpunit.integration.xml.dist` | integration suite, skipped without `CAMELIA_TEST_DSN` |
`mago.toml` pins `php-version = "8.4"`, matching the minimum supported version, so `mago fmt` and
the runtime agree on which syntax the package may ship.
## License
MIT. See [LICENSE](LICENSE).