Section 8.13. Saving Objects


8.13. Saving Objects

Previously, we covered how to save arrays in PHP using serialize( ), unserialize( ), urlencode( ), and urldecode( ). Saving objects works in the same wayyou serialize( ) them into a string to make a format that can be saved, then urlencode( ) them to get a format that can be passed across the web without problem.

For example:

     $poppy = new Poodle('Poppy');     $safepoppy = urlencode(serialize($poppy)); 

There is one special feature with saving objects: when serialize( ) and unserialize( ) are called, they will look for a _ _sleep( ) and _ _wakeup( ) method on the object they are working with, respectively. These methods, which you have to provide yourself if you want them to do anything, allow you to keep an object intact during its hibernation period (when it is just a string of data).

For example, when _ _sleep( ) is called, a logging object should save and close the file it was writing to, and when _ _wakeup( ) is called, the object should reopen the file and carry on writing. Although _ _wakeup( ) need not return any value, _ _sleep( ) must return an array of the values you wish to have saved. If no _ _sleep( ) method is present, PHP will automatically save all properties, but you can mimic this behavior in code by using the get_object_vars( ) methodmore on that soon.

In code, our logger example would look like this:

     class Logger {             private function _ _sleep( ) {                     $this->saveAndExit( );                     // return an empty array                     return array( );             }             private function _ _wakeup( ) {                     $this->openAndStart( );             }             private function saveAndExit( ) {                     // ...[snip]...             } 

Any objects of this class that are serialized would have _ _sleep( ) called on them, which would in turn call saveAndExit( )a mythical clean-up method that saves the file and such. When objects of this class are unserialized, they would have their _ _wakeup( ) method called, which would in turn call openAndStart( ).

To have PHP save all properties inside a _ _sleep( ) method, you need to use the get_object_vars( ) function. This takes an object as its only parameter and returns an array of all the properties and their values in the object. You need to pass the properties to save back as the values in the array, so you should use the array_keys( ) function on the return value of get_object_vars( ), like this:

     private function _ _sleep( ) {             // do stuff here             return array_keys(get_object_vars($this));     }



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net