NYCPHP Meetup

NYPHP.org

[nycphp-talk] Is serializing object/arrays for MySQL reliable?

csnyder chsnyder at gmail.com
Mon Oct 23 11:03:58 EDT 2006


> Cliff Hirsch wrote:
> Is serializing/unserializing object/arrays for storage/retrieval in a
> MySQL db truly reliable? It would be awfully handy, but the PHP
> manual notes list various issues that make me wary.

I do this to allow for an extendable data model. Aside from the usual
indexed fields (title, created, author) content tables also get a php
field, that stores a serialized standard object. When the record is
loaded, the php field is converted into a property on the object:
$object->local. So developers can write business logic that sets
$object->local->color, and that will persist and be available every
time the object is loaded.

As Hans points out, you have to be careful, and it isn't particularly
portable, but it has benefits in the areas of rapid prototyping and
systems that can adapt to changing needs.

Hans Zaunere wrote:
> -- unserialized objects aren't quite what you may expect them to be (ie, the
> definition of the class either has changed or doesn't exist)

Using standard objects is a good idea.

> -- it's slow

No doubt.

> -- it doesn't give you any type of normalization - ie, the object's data is
> relationally useless - and you end up having to do text matching to find
> anything

Yep. And you end up writing a function to generate a carefully crafted
LIKE statement to match key=value:

  function phplike( $key, $value ) {
    $like = '%"'.$this->esc($key).'";s:'.strlen($value).':"'.$this->esc($value).'"%';
    return $like;
  }

There is an understanding that local properties aren't going to be
indexed by the database, so aren't really useful in queries. The brute
force method encoded above is only for situations where you _really_
need to lookup objects by local property.

Not for the feint of heart, but also very useful.

-- 
Chris Snyder
http://chxo.com/



More information about the talk mailing list