Doctrine 2 Whats the Recommended Way to Access Properties?

后端 未结 6 1818
萌比男神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:26

    Here's why you can't use public properties: How can public fields “break lazy loading” in Doctrine 2?

    You are correct that __get() and __set() can make accessing the protected/private fields easier.

    Here's a simple example:

    public function __get($name)
    {
      if(property_exists($this, $name)){
        return $this->$name;
      }
    }
    

    Of course that gives access to all the properties. You could put that in a class that all your entities extended, then define non-assessable fields as private. Or you could use an array to determine which properties should be accessible:$this->accessable = array('name', 'age')

    There are plenty of ways to keep all properties protected and still have a reasonably easy way to get/set them.

提交回复
热议问题