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

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

问题描述

我记得在 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.

这篇关于Doctrine 2 访问属性的推荐方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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