Caching and serializationVersion

Notice: This thread is very old.
aeon
Member | 6
+
0
-

Hello everyone!

I dont get it. How to cache objects, retrieved from mysql database? In documentation about caching says about variable @serializationVersion, but nothing changes…
Error: You cannot serialize or unserialize PDO instances
Nette: version 2.0.3 released on 2012–04–04

models/Content.php

<?php

/**
 *	@serializationVersion 	123
 */
class Content extends Selection
{
	public function __construct(\Nette\Database\Connection $connection)
	{
		parent::__construct('Content', $connection);
	}
}

?>

Code, where i catch error:

<?php

$Content = $this->context->createContent()->order('Tag ASC');
$cache->save('Content', $Content);

?>

Please, tell me, what i am doing wrong and how to do right?
Thanks in advice! Hello from Kazakhstan!

Vojtěch Dobeš
Gold Partner | 1316
+
0
-

Hi :) I guess the problem is simply what the error message says: PDO cannot be serialized. Method __sleep() might help.

public function __sleep()
{
	$properties = Reflection\ClassType::from($this)->getProperties();
	unset($properties['connection']);
	return array_keys($properties);
}

Nevertheless I am not sure, if such object can be successfully restored from cache, because in complementory __wakeUp() magic method you aren't able to restore the connection object.

Vojtěch Dobeš
Gold Partner | 1316
+
0
-

Regarding @serializationVersion annotation: it is supposed to ensure proper validation in case the structure of the annotated class changes (such as adding or deleting properties which might lead to state, when cached data would'n t be compatible with the class anymore and cause an error during unserialization). You may cache objects without this annotation as well.

I am afraid caching of Selection instances or its descendants is not supported scenarion, but @hrach might know more.

Last edited by vojtech.dobes (2012-05-04 00:25)

aeon
Member | 6
+
0
-

to vojtech.dobes

Nette's Cache perfectly processing with custom classes, but variant with __sleep() not that way, i wanna go. But anyway, thank you for advice.

Vojtěch Dobeš
Gold Partner | 1316
+
0
-

Of course Nette caching works perfectly with custom classes. I just tried to point out, that caching of Selection instance (or its descendants) will work only with leaving $connection property from serialized output and then unserialization won't lead to well formed instance (because the instance itself is not sufficient to build the $connection instance from its data during unserialization). ;)

Last edited by vojtech.dobes (2012-05-04 11:01)

HosipLan
Moderator | 4668
+
0
-

You have a problem, because you're using bad design. You shouldn't serialize something, that contains connection to database. Such a class is by nature model that manipulates with data. You don't want to serialize such a thing.

You want to create new class, that will contain your data, and only data. And rethink your design.