Download the PHP package pechynho/polymorphic-doctrine without Composer
On this page you can find all versions of the php package pechynho/polymorphic-doctrine. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download pechynho/polymorphic-doctrine
More information about pechynho/polymorphic-doctrine
Files in pechynho/polymorphic-doctrine
Package polymorphic-doctrine
Short Description Doctrine polymorphic relations for Symfony applications.
License MIT
Informations about the package polymorphic-doctrine
Polymorphic Doctrine
A Symfony bundle that brings polymorphic relations to Doctrine ORM. It allows a single entity property to reference different entity types — with type safety, IDE support, and optional foreign key constraints.
The Problem
Doctrine ORM doesn't natively support a property that needs to reference multiple unrelated entity types. Imagine a Payment entity with a subject property that can point to either an EshopItem or a Subscription. Standard Doctrine associations require a fixed target type.
This bundle solves it with two approaches:
| Mode | DB Columns | Foreign Keys | Best For |
|---|---|---|---|
| Dynamic | {property}_type + {property}_id |
No | Flexible scenarios where FK constraints aren't needed |
| Explicit | {property}_type + one ID column per mapped type |
Yes | Scenarios requiring referential integrity |
Installation
Without Symfony Flex, add the bundle to config/bundles.php:
Quick Start
1. Mark the entity and define polymorphic properties
2. Generate reference classes (explicit mode only)
3. Work with polymorphic values
Polymorphic Modes
Dynamic Mode
Creates two columns per polymorphic property:
| id | dynamic_subject_type | dynamic_subject_id |
|---|---|---|
| 1 | eshop_item | 123 |
| 2 | subscription | 456 |
| 3 | NULL | NULL |
Pros: Simple setup, no class generation needed. Cons: No foreign keys — the database cannot enforce referential integrity.
Explicit Mode
Creates a type column plus a dedicated ID column for each mapped entity type:
| id | explicit_subject_type | explicit_subject_eshop_item_id | explicit_subject_subscription_id |
|---|---|---|---|
| 1 | eshop_item | 123 | NULL |
| 2 | subscription | NULL | 456 |
| 3 | NULL | NULL | NULL |
Pros: Foreign key on each ID column, referential integrity enforced by the database. Cons: Requires reference class generation, more columns per table.
Working with Polymorphic Values
Creating and Initializing
Updating
Reading
Tip: Always check
isNull()before callinggetValue().
Type-Narrowing with getValueAs()
The getValueAs() method provides a convenient way to retrieve the referenced entity with a narrowed return type. It accepts a class-string<T> and returns T, giving you full IDE autocompletion and static analysis support (PHPStan / Psalm).
The method throws a ReferenceResolutionException if:
- The value is
null— always checkisNull()first, or handle the exception. - The resolved entity is not an instance of the requested class.
Searching Polymorphic Values
The bundle provides two approaches for querying polymorphic properties via QueryBuilder.
Applier — Simple Approach
Directly modifies the QueryBuilder. Best for straightforward queries.
Builder — Advanced Approach
Returns expression objects with parameters that can be composed into complex queries.
Available Operations
| Method | Description |
|---|---|
eq($entity) |
Matches the given entity |
neq($entity) |
Does not match the given entity |
in(...$entities) |
Matches any of the given entities |
notIn(...$entities) |
Does not match any of the given entities |
isNull() |
Value is null |
isNotNull() |
Value is not null |
isInstanceOf(...$classes) |
Is an instance of the given type(s) |
isNotInstanceOf(...$classes) |
Is not an instance of the given type(s) |
Configuration
API Reference
Attributes
#[EntityWithPolymorphicRelations]
Marks an entity as containing polymorphic relations. Required for entity discovery.
#[DynamicPolymorphicProperty(array $mapping)]
Defines a dynamic polymorphic property (two columns: type + ID).
| Parameter | Type | Description |
|---|---|---|
$mapping |
array |
Map of type keys to entity class names |
$idProperty |
?string |
Custom ID property name |
$enableDiscriminatorIndex |
?bool |
Add index on discriminator column |
$enablePairIndex |
?bool |
Add index on type + ID pair |
#[ExplicitPolymorphicProperty(array $mapping)]
Defines an explicit polymorphic property (type column + dedicated ID column per mapped type).
| Parameter | Type | Description |
|---|---|---|
$mapping |
array |
Map of type keys to entity class names or detailed config |
$idProperty |
?string |
Default ID property name |
$idPropertyType |
?string |
Default ID property type |
$onDelete |
?string |
Foreign key ON DELETE action |
$onUpdate |
?string |
Foreign key ON UPDATE action |
$enableDiscriminatorIndex |
?bool |
Add index on discriminator column |
$enablePairIndex |
?bool |
Add index on type + ID pair |
Per-type detailed configuration in the mapping:
PolymorphicValueInterface
| Method | Return Type | Description |
|---|---|---|
isNull() |
bool |
Is the value null? |
isResolvable() |
bool |
Can the value be resolved to an entity? |
isLoaded() |
bool |
Is the entity already loaded in memory? |
getValue() |
?object |
Returns the referenced entity (lazy-loaded) |
getValueAs(string $fqcn) |
T |
Returns the entity narrowed to the given type, or throws |
update(?object $value) |
void |
Updates the reference to another entity or null |
setNull() |
void |
Sets the reference to null |
Services
| Service | Description |
|---|---|
PolymorphicValueFactoryInterface |
Creates polymorphic value instances |
PolymorphicSearchExprBuilderFactoryInterface |
Creates search expression builders |
PolymorphicSearchExprApplierFactoryInterface |
Creates appliers that directly modify QueryBuilder |
Console Commands
Important: After any change to explicit polymorphic property definitions, you must re-run the reference class generation command.
Troubleshooting
| Problem | Solution |
|---|---|
| Reference classes not found (explicit mode) | Run php bin/console pechynho:polymorphic-doctrine:generate-reference-classes then php bin/console cache:clear |
| Polymorphic properties not working | Verify the #[EntityWithPolymorphicRelations] attribute is on the entity, the bundle is registered, and discovery directories are configured |
| Slow queries | Enable indexes via enableDiscriminatorIndex and enablePairIndex on your attributes |
Requirements
- PHP >= 8.4
- Symfony 6.4 / 7.x / 8.x
- Doctrine ORM 2.19+ or 3.3+
License
MIT — see LICENSE.
Author
Jan Pech — [email protected]
All versions of polymorphic-doctrine with dependencies
doctrine/doctrine-bundle Version ^2.12
webmozart/assert Version ^1.11
symfony/cache-contracts Version ^3.6
symfony/service-contracts Version ^3.6
nette/php-generator Version ^4.1
spatie/php-structure-discoverer Version ^2.3
symfony/filesystem Version ^6.4 || ^7.0 || ^8.0
symfony/http-kernel Version ^6.4 || ^7.0 || ^8.0
symfony/property-access Version ^6.4 || ^7.0 || ^8.0
symfony/console Version ^6.4 || ^7.0 || ^8.0
symfony/dependency-injection Version ^6.4 || ^7.0 || ^8.0
symfony/options-resolver Version ^6.4 || ^7.0 || ^8.0
symfony/string Version ^6.4 || ^7.0 || ^8.0
symfony/config Version ^6.4 || ^7.0 || ^8.0
doctrine/orm Version ^2.19 || ^3.3