开发者

PHP: Is it bad design to serialize objects and stick them in the database for later?

I am planning and researching my switch from MySQL to MongoDB right now and I just had an interesting thoug开发者_如何学Goht... I have a bunch of hierarchical objects that I need to store in the database. My current method is to have a bunch of embedded documents in a collection. They will never need to be searched for. Would it possibly make sense just to serialize the PHP objects, stick them in the DB, and then unserialize them back into PHP objects when I want to use them? The alternative is using Doctrine as my ORM.

My programming intuition tells me that this is bad design and is limiting, but I feel like serializing and unserializing would be very fast and eliminate the need for an ORM.

What's your opinion? Good design or bad design?


In many cases this would be considered bad design, but it could work if all of the following apply:

  1. You don't need to search on them
  2. You can accept (potentially) limited ability to query on them
  3. You don't need relational integrity or other constraints enforced by the RDBMS
  4. You know you'll never need to read them in a different language
  5. You're confident that you'll know how to deserialize, version, and migrate them properly when you update your class definition
  6. You're confident that the PHP serialization format will be stable across releases (or you are willing to write migration code, or it's a short-term project and you don't care)
  7. You're willing to accept a minor performance penalty (SELECT + deserialize() will be slower than just SELECT)


Why use a database if you can't query it ?


It kind of depends entirely on what you intend to do.

If it's always the same object each request deals with or there are no relationships between each request, it might be ok.

But to me there are a lot of downsides:

  • You might want to do something more advanced to the objects later
  • Serialized objects are kind of unreliable (not exactly ACID compliant)
  • There's nothing else that can read a serialized php object, you might want to use something else instead.


Serializing objects is VERY useful when you have to cache things, such as RSS feeds.

I find it good use to serialize it, but I would also make sure that that can never be editing as a string without unserializing it first!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜