Doctrine 2 Whats the Recommended Way to Access Properties?(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 访问属性的推荐方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Doctrine 2 访问属性的推荐方式是什么?
基础教程推荐
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php中的foreach复选框POST 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- php中的PDF导出 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
