Persistence / ORM
Value objects can be used directly as property types in entities. The ORM stores the scalar value in the column and creates the value object again when the entity is loaded.
Supported are all types implementing StringValueObject, IntValueObject, FloatValueObject or BoolValueObject. No attribute is required.
Entity
use n2n\reflection\ObjectAdapter;
use valobj\string\Email;
use valobj\string\Name;
use valobj\string\Phone;
use valobj\string\Text;
class Customer extends ObjectAdapter {
public int $id;
public Name $firstName;
public Name $lastName;
public Email $email;
public ?Phone $phone = null;
public ?Text $notes = null;
public Price $creditLimit; // final class Price extends TypicalTwoDigitDecimal {}
}
CREATE TABLE `customer` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(80) NOT NULL,
`last_name` VARCHAR(80) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`phone` VARCHAR(50) NULL DEFAULT NULL,
`notes` TEXT NULL DEFAULT NULL,
`credit_limit` DECIMAL(8,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Choose the column length according to the MAX_LENGTH of the value object (e.g. Name::MAX_LENGTH = 80).
Persist
$customer = new Customer();
$customer->firstName = Name::from('Hans');
$customer->lastName = Name::from('Muster');
$customer->email = Email::from(' Hans@Muster.ch ', true);
$customer->creditLimit = Price::from(5000.0);
$tx = $tm->createTransaction();
$em->persist($customer);
$tx->commit();
Stored row:
| id | first_name | last_name | phone | notes | credit_limit | |
|---|---|---|---|---|---|---|
| 1 | Hans | Muster | hans@muster.ch | NULL | NULL | 5000.00 |
Load
$customer = $em->find(Customer::getClass(), 1);
$customer->email; // Email("hans@muster.ch")
$customer->email->toScalar(); // "hans@muster.ch"
$customer->phone; // null
Update
Value objects are immutable — assign a new instance. The ORM detects the change:
$tx = $tm->createTransaction();
$customer = $em->find(Customer::getClass(), 1);
$customer->phone = Phone::from('079 123 45 67', true);
$tx->commit();
Queries
Pass a value object or a scalar:
$customers = $em->createSimpleCriteria(Customer::getClass(),
['email' => Email::from('hans@muster.ch')])
->toQuery()->fetchArray();
$customers = $em->createSimpleCriteria(Customer::getClass(), ['email' => 'hans@muster.ch'])
->toQuery()->fetchArray();
$customers = $em->createSimpleCriteria(Customer::getClass(), ['phone' => null])
->toQuery()->fetchArray();
Value object as id
use n2n\persistence\orm\attribute\Id;
use valobj\string\NonSpecialCharsString;
final class CountryCode extends NonSpecialCharsString {
const MIN_LENGTH = 2;
const MAX_LENGTH = 2;
}
class Country extends ObjectAdapter {
#[Id(generated: false)]
public CountryCode $code;
public Name $name;
}
$country = $em->find(Country::getClass(), CountryCode::from('ch'));
Corrupted data
If the database contains a value the value object does not accept (e.g. an invalid email that was inserted by an SQL script), loading the entity throws an n2n\persistence\orm\CorruptedDataException.
Together with n2n Bind
Unmarshal the request data and assign the value objects directly to the entity:
$result = Bind::attrs($body->parseJson()) // ParamBody $body
->prop('firstName', Mappers::unmarshal(Name::class), Validators::mandatory())
->prop('lastName', Mappers::unmarshal(Name::class), Validators::mandatory())
->prop('email', Mappers::unmarshal(Email::class), Validators::mandatory())
->prop('phone', Mappers::unmarshal(Phone::class))
->toObj($customer)
->exec();
if ($result->isValid()) {
$em->persist($customer);
}
Not supported
Arrays like NbIdArray or DateArray cannot be used as entity property types. Use a relation instead.