重载类属性时验证 setter 的 php 最佳实践
我有一个使用 __set 魔术方法的类。该类的属性之一只能设置一定范围的字符串值,我能想到的最好的例子是 mysql 数据类型 ENUM('value_one','value_two','value_third')。
我是否可以在 __set 方法中放置条件语句来区分正在设置的属性以及该值对于该属性是否有效?
__set 方法中的大型 switch 语句是否被认为是草率的做法,它们是产生所需结果的更好方法吗?
谢谢, 本
I have a class that uses the __set magic method. One of the properties for the class can only be set with a certain range of string values, the best example I can think of is the mysql datatype ENUM('value_one','value_two','value_three').
Would I place conditional statements within the __set method to distinguish between which property is being set and whether the value is valid for that property?
Are large switch statements inside a __set method considered sloppy practice, is their a better way of producing the desired results?
Thanks,
Ben
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一部分是,第二部分不是。
您的
__set
方法应确定尝试设置哪个变量,然后将其余功能传递给私有设置器setPspecialVar
。然后,setPspecialVar
将包含特定于验证该变量的逻辑,并且如果传递了无效值,则可能会引发异常。或者,您可以将私有设置器设为公共,从而允许两种方式设置变量,但这并不理想,因为两种设置值的方式不是干净的设计。
Yes to the first part, no to the second.
Your
__set
method should determine which variable is trying to be set and then pass off the rest of the functionality to a private settersetParticularVar
.setParticularVar
will then contain the logic specific to validating that variable and can throw an exception if an invalid value is passed.Alternatively, you could make the private setter public instead, allowing two ways to set the variable but this is not as desirable as two ways to set a value is not as clean a design.
__set
函数可以检查是否存在名为类似于presetVariableName
的方法,该方法被调用并将新值作为参数传递。然后,该函数可以执行验证逻辑,并返回
true
或false
以确定其是否有效。The
__set
function could check for the existance of a method named similar topresetVariableName
, which is called and passed the new value as a parameter.That function could then perform the validation logic, and return
true
orfalse
as to whether it's valid or not.