I'm implementing a customized priority queue based on PHP's SPLPriorityQueue in a Zend Application. It contains custom objects, PriorityQueueItens, instead of pure values aside the priority value. When storing the queue in APC (or memcache) I have to make sure the queue and its items are serializable, so I've set them to implement the Serializable interface using code from the upcoming Zend Framework 2.
public function serialize()
{
$data = array();
开发者_开发技巧while ($this->valid()) {
$data[] = $this->current();
$this->next();
}
foreach ($data as $item) {
$this->insert($item['data'], $item['priority']);
}
return serialize($data);
}
public function unserialize($data)
{
foreach (unserialize($data) as $item) {
$this->insert($item['data'], $item['priority']);
}
}
After fetching the queue from APC and retrieving the top item in the priority queue, using $this->extract()
, I don't get the item but the array that is created during serialization.
So, instead of a PriorityQueueItem
, the base class I use for objects stored in the queue, I get an associative array with indices data and priority (similar to the array in the serialize function). To get the actual item I need to retrive the data part of the array instead of treating the returned item as an item, which is how it works when not storing the queue in APC and how I assumed it would work now as well.
Is this a feature of serialization of objects or am I approaching this in a wrong way?
Update: The issue here was that I had a separate function that did extra cruft besides the extract()
. This function returned the item as an array, but as soon as I called extract()
explicitly I got the item as expected. Are there certain precautions to take with public functions in objects that have been serialized?
You mixed/switched this probably:
In your code you are serializing the $data
array, not "your object". I'm not entirely sure of this because I do not know what the insert()
function is for.
But for the serialize in an object with the serializable
interface you will get back what has been returned from object::serialize()
.
As you serialize an array, you will get the serialized array back. PHP in the background is taking care that this was stored as your object.
精彩评论