Skip to content

Commit

Permalink
Merge pull request #22 from chadyred/doc/discriminator-map
Browse files Browse the repository at this point in the history
docs(abstract): How to deal with abstract
  • Loading branch information
strider2038 authored Jan 6, 2022
2 parents 7186db9 + abcd79a commit 13a9eab
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,59 @@ ODMType::registerODMType(

You can see example of Symfony 4 application with using ODM library in this [directory](https://github.com/goodwix/doctrine-json-odm/tree/master/tests/Resources/Symfony).

## Deal with abstract

As an `abstract` class could not be created as an instance, each concrete children have to be mapped into the abstract class.

Indeed, the `Symfony Serializer` must know the real type in this case through a discriminator field to determine the real object behind
the stored data. For that, it use `Symfony\Component\Serializer\Annotation\DiscriminatorMap`. More info is available [here](
Maybe this way : [Symfony serializer : discriminator](https://symfony.com/doc/current/components/serializer.html#serializing-)

For example, if we have an abstract and 2 children

```php
<?php
declare(strict_types=1);
namespace App\Whatever;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
#### PHP8 Attribute ####
#[DiscriminatorMap(
typeProperty: 'type',
mapping: [
'myChildTypeName' => 'App\Whatever\Child',
'myChild2TypeName' => 'App\Whatever\Child2',
]
)]
####> PHP8 Attribute ####
#### PHP < PHP8 ####
/**
* @DiscriminatorMap(typeProperty="type", mapping={
* "myChildTypeName"="App\Whatever\Child",
* "myChild2TypeName"="App\Whatever\Child2"
* })
*/
####> PHP < PHP8 ####
abstract class MyAbstract
{
}
class Child extends MyAbstract
{}
class Child2 extends MyAbstract
{}
```


## Contribution

You can run `composer lint` before pushing to repository to ensure that there are no code style errors.
Expand Down

0 comments on commit 13a9eab

Please sign in to comment.