doctrine / mongodb-odm

The Official PHP MongoDB ORM/ODM
https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/
MIT License
1.09k stars 502 forks source link

Detect field type with property type #2661

Open GromNaN opened 3 months ago

GromNaN commented 3 months ago

Feature Request

Q A
New Feature yes
RFC yes
BC Break no

Summary

In metadata, the default type of fields is string, regardless of the type of field property. I propose to inspect the property types when the field type is not defined. The would only support simple types (maybe with extension point):

property field
int int
string string
float float
DateTime date
DateTimeInterface date_immutable
DateTimeImmutable date_immutable
ObjectId object_id

Benefit: no need to declare the field type.

Usage

#[Document]
class User
{
    #[Id]
    public string $id;

    #[Field]
    public string $name;

    #[Field]
    public DateTimeImmutable $createdAt;

    #[Field]
    public int $level;
}
IonBazan commented 3 months ago

Sounds useful and I think ORM had it for a while now. Do you mind if I try to implement this one if you haven't started yet? Otherwise, let me know if you need any help.

GromNaN commented 3 months ago

@IonBazan I haven't started investigating yet. Do so if you feel inspired.

malarzm commented 3 months ago

We already have that thanks to #2411 and @franmomu :)

https://github.com/doctrine/mongodb-odm/blob/8b542f4c5b9239a3083a375894c4249e922b315d/lib/Doctrine/ODM/MongoDB/Mapping/ClassMetadata.php#L2672-L2679

GromNaN commented 3 months ago

We already have that thanks to #2411 and @franmomu :)

Perfect. How could I have missed it despite it being well documented? I may simplify some doc examples to leverage this feature.

One thing that could be improved is reading the phpdoc for @var Collection<Class> annotation that would indicate the targetDocument of #[EmbedMany] and #[ReferenceMany]. As long as we don't have a native PHP solution for generics.

IonBazan commented 3 months ago

Thanks @malarzm, looks like I forgot about this feature. Perhaps it could be extracted to a separate class as ClassMetadata is already massive. We could also port https://github.com/doctrine/orm/pull/10313 which allows customization of this functionality.