Doctrine 2什么是推荐的访问属性的方式? [英] Doctrine 2 Whats the Recommended Way to Access Properties?

查看:109
本文介绍了Doctrine 2什么是推荐的访问属性的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得在Doctrine 2模型中读过,我不应该将属性/字段设置为public。你会怎么暴露这些领域?沙箱使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆