YAML或serialize()将数据存储在MySQL中
我正在尝试将临时数据(例如购物车产品、session_data)存储在数据库中。我为此选择了 YAML 而不是 serialize() 函数。因为 YAML 数据易于人类读取并且可以在编程语言之间移植。
如果我将临时数据存储在数据库中,YAML 是否会遇到麻烦?
I am trying store temporary data (such as cart products, session_data) in DB. And I choosed YAML for this instead of serialize() function. Because YAML data is easily readable by human and portable between programming languages.
Am I in trouble with YAML if I store my temprory data in database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就我个人而言,我会使用序列化有两个原因:
关于第二点。 Serialize 不仅仅转换为字符串,它还记录类型,并且 PHP 调用对象上的函数,因此您可以选择要序列化的内容以及反序列化时对数据执行的操作。
请参阅:__sleep 和 __wake
直接从数据库读取可能并不容易,但编写一个可以将其取出、反序列化并对数据执行 print_r 以查看存储内容的脚本不需要两分钟。
Personally I would use serialize for two reasons:
In regards to the second point. Serialize doesn't just convert to a string it records the type as well and PHP calls functions on objects so you can choose what to serialise and what do do with the data when you unserialise it.
See: __sleep and __wake
It may not be easy to read directly from the database but it wouldn't take two minutes to write a script that could pull it out, unserialise it and do a print_r on the data to view what's stored.
就我个人而言,我不会使用 YAML。它太依赖于格式(需要换行、空格等),并且 PHP 中没有本地解析器。相反,我会使用 JSON 来实现此目的。它在本地处理起来很简单,并且非常易于人类阅读(不如 YAML,但比序列化的要好得多)。这是两全其美的。
但是,话虽如此,您确实应该问自己一个问题:为什么要在数据库的字段中存储复杂数据结构的序列化表示……在大多数情况下,存储规范化表示可能会更好数据(因此可以轻松搜索等)。存储序列化数据并不是“坏”,但根据您想要执行的操作,它可能不是最佳或正确的选择。它通常比使用实体属性值存储要好得多,但您需要真正考虑您正在做什么才能决定它是否正确。
Personally, I wouldn't use YAML. It's too format-dependent (Requiring new lines, whitespace, etc) and there's no native parser in PHP. Instead, I'd use JSON for this. It's trivial to handle natively, and is quite human readable (no as much as YAML, but much more so than serialized). It's the best of both worlds.
But, with that said, you really should ask yourself the question as to why you want to store a serialized representation of a complex data structure in a field in the DB... For most cases, it might be better to store a normalized representation of the data (so it's searchable easily, etc). It's not "bad" to store serialized data, but it might not be optimal or the right choice depending on what you're trying to do. It's generally far better than using an Entity-Attribute-Value store, but you need to really think about what you're doing to decide if it's the right thing.
只要确保您逃脱了所有潜在危险(即用户输入),就可以了。
Just make sure you are escaping everything potentially dangerous i.e. user input and you are fine.