Doctrine 2什么是推荐的访问属性的方式? [英] Doctrine 2 Whats the Recommended Way to Access Properties?
问题描述
get *()
& set *()
方法。这是最好的主意吗?它很麻烦使用魔术方法 __ get()
__ set()
将使类似于设置字段public? 你的建议是什么?
这就是为什么你不能使用公共属性:Doctrine 2中的公共领域如何打破懒惰加载? / a>
你是正确的, __ get()
和 __ set() code>可以更容易地访问
受保护的
/ private
字段。
这是一个简单的例子:
public function __get($ name)
{
if(property_exists($ this,$ name)){
return $ this-> $ name;
}
}
当然可以访问所有的属性。您可以将其放在所有实体扩展的类中,然后将不可评估字段定义为 private
。或者您可以使用数组来确定哪些属性应该可访问: $ this-> accessable = array('name','age')
有很多方法可以保护所有属性,并且仍然有一个相当简单的方法来获取/设置它们。
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?
Whats your recommendation?
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.
这篇关于Doctrine 2什么是推荐的访问属性的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!