marble / entity-manager
An ORM-less entity lifecycle manager for PHP.
Installs: 55
Dependents: 1
Suggesters: 0
Security: 0
Stars: 3
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/marble/entity-manager
Requires
- php: ^8.2
- psr/event-dispatcher: ^1.0
- sebastian/comparator: ^4.0|^5.0
- symfony/var-exporter: ^7.3|^8.0
Requires (Dev)
- dg/bypass-finals: ^1.9
- mockery/mockery: ^1.4
- phpunit/phpunit: ^10
- symfony/uid: ^6.2
- vimeo/psalm: ^5.0|^6.0|^7.0
Suggests
- symfony/uid: If you want to use the provided UUID and ULID implementation of the Identifier interface.
README
This library provides some of the great features of ORM frameworks — entity manager, unit of work, identity map, repository factory, query caching — without the object-relational mapping itself. It’s up to you to implement the actual reading and writing of entity data from and to whatever persistence layer you’re using.
- Unit of work: Bundles all your database operations into a single transaction-like flush, ensuring data consistency.
- Identity map: Ensures that each unique entity is instantiated only once per session, preventing conflicting object states.
- Automatic change tracking: Automatically detects modifications to your entities, so you only save what has actually changed.
- Ordered flushes: Intelligently calculates the correct order to persist entities based on their associations, handling dependencies for you.
- Persistence-agnostic: Since you implement the readers and writers, you can use any storage engine — SQL, NoSQL, or even external APIs — while keeping your domain logic clean.
Why Marble?
I love Doctrine ORM as much as the next guy, but often enough the object-relational mapping part of it is just overly constrained (1 property = 1 column) and overly constraining (Doctrine collections all over your domain code). Its configuration, especially if you want to get around those constraints, can get very (very) elaborate.
Moreover, ORM libraries are limited to relational (i.e. SQL-based) storage engines. Add NoSQL or external APIs into the mix, and you'll need to bring in additional entity-managing libraries to bridge the gap.
Marble gives you full control over how your data is saved and loaded, without sacrificing the benefits of a robust unit of work and identity map.
Installation
Use Composer to install: composer require marble/entity-manager
This library requires PHP 8.2.
Note: if you’re building a Symfony application, consider installing the bundle instead.
Getting started
- All your entity classes should implement the
Entityinterface. For identifiers you may use the providedSimpleIdor Uid classes, or any other implementation of theIdentifierinterface. - Create a class that implements
EntityReaderfor every entity class that you want to fetch from your application code or from other readers. See Fetching for more details. - Create one or more classes that implement
EntityWriter. Typically you’ll have either a single writer for all entities, or a writer per entity class except those that are always written and deleted by other writers. See Persisting and Removing for more details. - Implement the
EntityIoProviderinterface and have it return the correctEntityReaderandEntityWriterfor a givenEntity. Of course one class may implement both interfaces.
How it works
Persisting
- To persist a newly created entity,
addit to its repository or pass it toEntityManager::persist. Preexisting, fetched entities don’t need to be re-registered; any changes to them will be automatically detected. To actually write data changes to your persistence layer, callEntityManager::flush; until then all changes are in memory only. Note that an entity’s writer will only be called if the entity indeed has changes or must be removed. - Multiple entities in the same entity class hierarchy must never have the same identifier. It’s okay if new entities don’t have an identifier yet, but once an entity is persisted it must have an identifier.
- A flush order is calculated by sorting known entities such that a given entity’s associations are
all ranked higher than the entity itself. As such, when persisting an entity in
EntityWriter::write, its associated entities will have been passed to their writers already, and will have an id. This algorithm does not allow circular entity associations. - You may use a writer to persist not just its own entity but particular associated entities ("child entities")
as well, e.g. an aggregate root’s writer also persisting other entities in the aggregate. Make sure
to call
markPersistedon the passedWriteContextto let the unit of work know that these were indeed persisted.EntityIoProvider::getWritercan returnnullfor entity classes that are always persisted by other writers. - Your entity writer should throw an
EntitySkippedExceptionwhen you need to leave the writing or removing of the entity to a parent entity’s writer later in the flush order. The library will check that all necessary writes and removals are done by the end of the flush.
Fetching
- Fetch entities by getting their repository from the entity manager and passing any kind of object
to one of the
fetch*methods. The object represents the query to be executed. It will be passed to the entity reader, where you should handle it appropriately. A special case is objects implementing theIdentifierinterface; these are only allowed on thefetchOnemethod. - Your query classes may be as simple or complex as you find helpful, and may carry any information needed
for the corresponding entity reader to do correct data retrieval (e.g. construct SQL statements),
including sorting and pagination. A
Criteriaclass is provided by this library, to represent a set of values to filter on. - Entity readers should not instantiate entities themselves; instead, they pass identifier/data combinations
into the
DataCollector. After the entity reader is done with data retrieval, the repository will make sure entities are instantiated, registered in the unit of work, added to the identity map and returned. - When fetching an entity, use the passed
ReadContextto access other repositories and fetch associated entities through them. Any associated sub-entity is replaced with its equivalent in the identity map, if it exists there already. So even with nested associations, only one instance of a particular entity will exist at any time. - You may use a custom repository for a particular entity class by having
EntityIoProvider::getCustomRepositoryreturn either an instantiated custom repository, or its class name. It must extendCustomRepository, and it should use thefetchOneandfetchManymethods of its parent. TheEntityReaderwill still handle all actual read operations (e.g. database interaction); custom repositories allow you to hide query construction details from domain code. Custom repositories may also simplify dependency injection, e.g. injecting into a service only the specific repositories it requires, instead of the entity manager. - IMPORTANT: One major limitation of this library compared to some other ORM libraries, is
that all
fetch*calls to the repository are forwarded to your entity reader. This means queries only operate directly on the persistence layer, and will ignore in-memory, pre-flush changes and additions in the unit of work. There is currently no extension point in the library to circumvent this limitation.
Removing
- To remove an entity,
removeit from its repository or pass it toEntityManager::remove. Again, only on flush are deletions actually executed throughEntityWriter::delete. - You may use a writer to delete not just its own entity but associated sub-entities as well, whether
explicitly or via database-level cascade rules. Make sure to call
markRemovedon the passedDeleteContextto let the unit of work know that these were indeed removed. - Removed entities are removed from the identity map. Fetching the same entity again will return a new instance.
License
Marble is open-sourced software licensed under the MIT license.
About
Made by a Dutch guy in his spare time, with some frustrations towards (as well as love for) Doctrine ORM.