Doctrine 2 访问属性的推荐方式是什么?

2022-01-03 00:00:00 php doctrine-orm getter-setter

我记得在 Doctrine 2 模型中读到过,我不应该将属性/字段设置为公开.那么你将如何公开这些字段?沙箱使用 get*() &set*() 方法.这是最好的主意吗?它非常麻烦.使用魔术方法 __get() __set() 会使类似于设置字段公开的事情吗?

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*() & set*() methods. Is that the best idea? Its very cumbersome. Using magic methods __get() __set() will make things similar to setting fields public?

您有什么建议?

推荐答案

这就是你不能使用公共属性的原因:Doctrine 2 中的公共字段如何打破延迟加载"?

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

您是正确的,__get()__set() 可以访问 protected/private 字段更容易.

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

这是一个简单的例子:

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

当然,这可以访问所有属性.您可以将其放在所有实体都扩展的类中,然后将不可评估的字段定义为 private.或者你可以使用一个数组来确定哪些属性应该是可访问的:$this->accessable = array('name', 'age')

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.

相关文章