简体   繁体   中英

Doctrine ORM - How to persist static properties

I have been using Doctrine ORM for a while an now, I have a class-level property ( static property) which I need to persist in MySQL database and I would like to now how.

Class Student {

    private $name;
    public static $instances = array();

    public __construct($name) {

        $this->name = $name;
        self::$instances[] = $this->name;

    }

}

According to the Documentation ( Basic Mapping > Property Mapping ):

The next step after marking a PHP class as an entity is mapping its properties to columns in a table.

To configure a property use the @Column docblock annotation. The type attribute specifies the Doctrine Mapping Type to use for the field. If the type is not specified, string is used as the default.

It sounds like doctrine only supports object-level properties. But as the title reads " Basic Mapping ", I think there should be some type of " Advanced Mapping " that maybe covers static properties. I searched for that with no success.

Also it is not listed at Limitations and Known Issues

Question

Someone please let me know if this is possible to persist static properties in Doctrine 2, and if not, How should I accomplish this task? Any work arounds or something?

Unfortunately, my reputation does not allow commenting, so I have to write this as an answer. Sorry for that.

My first thought is that you are going about this the wrong way. Can you give some more information what the "instances" actually are? It looks like it's a list of all student names in the system? Why do you need to have this as a static class property?

Some thoughts:

1)

It sounds like doctrine only supports object-level properties.

Yeah, I think that's correct, but I don't see the use case for anything else really. To me it feels intuitively wrong to have Static data in a database as it's not meant to change (very) often. Can't you just have your values in the code or in a config file (if there are too many). If, on the other hand, your data is changing often, then it's not Static (<=> not changing).

2) If you really want to map it and have it in the db I believe association mappings is the way to go (one-to-many or many-to-many). Ie, you should move it to its own Entity that has a relation to the Student entities. In your case it looks like you should create a University entity that has a list of all students. And that way you can iterate to build a list of all names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM