Zend_Validate 避免代码重复的好策略
我目前正在构建两个扩展 Zend_Validate_Abstract
的自定义验证器,它们分别命名为 Lib_Validate_TimeAfter
和 Lib_Validate_TimeBetween
。这些名称非常简单,第一个用于测试日期/日期时间/时间是否在另一个日期/日期时间/时间之后,第二个用于测试日期/日期时间/时间是否在其他两个日期/日期时间/时间之间。
这两个验证器都依赖于名为 _buildDate($value)
的相同方法,该方法采用 datestamp
、hourstamp
形式的值(hh:mm
或 hh:mm:ss
)、时间戳
或 ISO_8601 时间戳
并将其转换以可用的日期格式。
由于我不想重复自己并将该方法复制/粘贴到我的两个验证器中,因此我一直在寻找最好的方法来做到这一点。
我现在正在考虑的途径是开发某种类帮助器,我的验证器将能够使用它(一种混乱的做事方式,因为它添加了不必要的依赖项),或者我可以通过构建一个其他验证器验证日期/日期时间/时间,然后扩展我的两个验证器,因为我可以共享方法 _buildDate($value)
,但我认为我并不真正需要验证器。
那么,构建这种代码以避免重复(DRY)的好方法是什么(我并不是真的在寻找做事的“众神之道”)?
I'm am currently building two custom validators that extends Zend_Validate_Abstract
which are named respectively Lib_Validate_TimeAfter
and Lib_Validate_TimeBetween
. The names a pretty straight forward, the first one is used to test if a date/datetime/time comes after an other one and the second is used to test if a date/datetime/time comes between two other date/datetime/time.
Both of those validators would rely on the same method named _buildDate($value)
which take a value in the form of a datestamp
, a hourstamp
(either hh:mm
or hh:mm:ss
), a timestamp
or an ISO_8601 timestamp
and convert it in a usable date format.
Since I dont want to repeat myself and copy/paste the method in both of my validator, I was looking for the best way to do it.
The avenues I am looking at right now would be to develop somekind of class helper that my validators would be able to use (kind of messy way of doing things since it add unessesary dependencies) or I could add an other layer of abstraction by building an other validator that validate date/datetime/time and then extend my two validators on that since I could share the method _buildDate($value)
, but then I don't think I would really need the validator.
So, what would be a good way (I am not really looking for the "Way of the gods" of doing thing) to structure that kind of code to avoid repetition (DRY)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想要构建一个验证器而不是两个,您可以在其中传递 dateBefore、dateAfter 这两个验证器都是可选的。如果您仅传递 dateBefore,则 $value 在该日期之后才有效;如果您传递两者,则该值必须在它们之间;如果您仅传递 dateAfter,则该值必须在该日期之前。
这将是灵活的、清晰的、通用的、更少的代码,甚至可以多涵盖一种情况。
You might want to build one validator instead of two, where you can pass in a dateBefore, dateAfter which are both optional. If you pass only dateBefore, your $value will be valid if it is after that date, if you pass in both, it will have to be between them and if you pass in only dateAfter, the value will have to be before that date.
This would be flexible, clear, generic, less code and even cover one more case.
一个类
Lib_Validate_Common
怎么样,它扩展了Zend_Validate_Abstract
,它有你的通用方法。并且Lib_Validate_TimeAfter
和Lib_Validate_TimeBetween
扩展了Lib_Validate_Common
。What about a class
Lib_Validate_Common
which extendsZend_Validate_Abstract
which has your common method. AndLib_Validate_TimeAfter
andLib_Validate_TimeBetween
extendsLib_Validate_Common
.