feat: initial commit of camelia/orm

Attribute-mapped Active Record ORM for MariaDB/MySQL over PDO.

- Attribute-driven metadata: TableName, PrimaryKey, AutoIncrement, Column,
  Guarded, Ignore, Required, Enum, Nullable, Length, Precision, Unique,
  UniqueGroup, Index, MaxLength.
- Relationship mapping: BelongsTo, HasOne, HasMany, BelongsToMany with
  batched eager loading and a 3-level depth limit.
- Orm entry point with fromArray, fromPdo, fromEnv and nested transactions.
- Immutable Query with Cond operators and GroupCond grouping.
- Repository read and write API, pagination, and typed exception hierarchy.
- Declares PHP >=8.3; Mago and PHPStan pin the parser to 8.3.
- MIT license.
This commit is contained in:
dgarcia committed 2026-11-15 10:14:22 -03:00
commit 66e93e3070
97 files changed
+12188

No files matched your search

+148
View File
@@ -0,0 +1,148 @@
# camelia-orm
Lightweight attribute-mapped Active Record ORM for MariaDB/MySQL over PDO, by Dr2g Sistemas.
- **Package:** `camelia/orm` · **Namespace:** `Camelia\Orm`
- **PHP** `>=8.3`, 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: 80300` |
| `phpunit.xml.dist` | unit suite |
| `phpunit.integration.xml.dist` | integration suite, skipped without `CAMELIA_TEST_DSN` |
`mago.toml` pins `php-version = "8.3"`. Do not raise it to 8.4: with 8.4 the formatter emits
`new Foo()->bar()`, which the package cannot ship because it promises PHP 8.3 support.
## License
MIT. See [LICENSE](LICENSE).