Skip to main content

Installation

composer require dirthara/entity

Requirements

RequirementWhy
PHP 8.5Reflection writes raw property values, and the code uses new without parentheses and typed class constants.
dirthara/database ^0.1Owns the connections, drivers and query builder this package maps onto.
dirthara/collection ^0.1A result set is returned as a collection rather than an array.

Composer installs both Dirthara packages for you. This package never touches PDO itself, but dirthara/database does, so each database needs its own PDO extension. Install only the ones you use:

DatabaseExtension
MySQLpdo_mysql
PostgreSQLpdo_pgsql
SQLitepdo_sqlite
SQL Serverpdo_sqlsrv

Wiring it up

An EntityManager needs four collaborators: the Database to run queries on, a registry that reads mapping from your classes, a hydrator that fills an entity from a row, and a persister that writes one back.

use Dirthara\Entity\EntityManager;
use Dirthara\Entity\Metadata\MetadataFactory;
use Dirthara\Entity\Metadata\MetadataRegistry;
use Dirthara\Entity\Naming\DefaultNamingStrategy;
use Dirthara\Entity\Hydration\ReflectionHydrator;
use Dirthara\Entity\Persistence\ReflectionPersister;
use Dirthara\Entity\Type\TypeRegistry;

$types = new TypeRegistry();

$entities = new EntityManager(
database: $database,
metadata: new MetadataRegistry(new MetadataFactory(new DefaultNamingStrategy(), $types)),
hydrator: new ReflectionHydrator(),
persister: new ReflectionPersister(),
);

$database is the Dirthara\Database\Database from dirthara/database. See that package's installation page for building one.

CollaboratorInterfaceWhat to replace it for
MetadataRegistrynone, it is a final classNothing; it caches MetadataFactory per class.
DefaultNamingStrategyNamingStrategyA different table or column convention.
TypeRegistrynone, it is a final classRegistering your own converters, or replacing a built-in.
ReflectionHydratorHydratorFilling entities some other way than reflection.
ReflectionPersisterEntityPersisterWriting entities some other way than reflection.
tip

A framework integration would build this once and hand the EntityManager to application code. Nothing here opens a connection, and metadata is read the first time a class is asked for, so building it early costs nothing.

A TypeRegistry with nothing passed to it already handles every scalar, plus any backed enum you map. Registering is for your own types and for replacing a built-in; see Converters.

Next: Getting started.