Doctrine 2 Whats the Recommended Way to Access Properties?

后端 未结 6 1823
萌比男神i
萌比男神i 2020-12-14 20:04

I remember reading that in Doctrine 2 models, I should not set properties/fields public. How then would you expose these fields? The sandbox used get*() & <

6条回答
  •  死守一世寂寞
    2020-12-14 20:32

    Personally, I don't like boilerplate code with trivial purpose - it makes the code ugly and tiresome to read. Therefore, I strongly prefer __get/__set. That said, they do have a few drawbacks:

    • they are significantly slower than normal function calls, though not so much that it should make a difference in practice, as database access is several orders of magnitude slower
    • __get/__set only gets called when the field is not visible; if you access properties in the code of the entity class, they do not get called, and the proxy has no chance to load itself. (Doctrine tries to avoid this by instantly loading the proxy as soon as one of its public methods are called, but there are some exceptions such as __construct or __wake where that would not make sense, so you can get into trouble by e.g. reading a field in the constructor.)
    • PHP has some confusing behaviors related to magic methods - e. g. empty($entity->field) will not invoke __get (and thus it will break proxy behavior if used)

提交回复
热议问题