PHP serializing and unserializing with circular references

In Aomebo Framework, which is my PHP MVC framework. Runtimes can be serialized and unserialized to improve speed.

Runtimes could contain a list of Routes, which is used for URL routing and URL generation. The Routes contain a reference to the Runtime that they are associated with.

So we have the following relationships.

Runtime -> Routes, Route -> Runtime = Runtime <-> Route

In order to improve the speed of the framework I was implementing a serializing and unserializing feature. Serializing Runtimes without Routes worked from scratch. When a Runtime contain at least one Route, the php execution stopped without any notice (Fatal Error). Was hard to debug.

I solved it by doing the following.

Serializing:
1. Runtime Routes are stored outside of Runtimes.
2. Serialize all Runtimes without their Routes.
3. Replace the references to Runtimes in Routes with class-name strings only.
4. Serialize all Routes.

Unserializing:
1. Unserialize all Runtimes (no Routes were stored in Runtimes).
2. Unserialize all Routes, references are only class-name strings now.
3. Iterate through Routes and replace reference class-name strings with instanciated Runtimes based on class-name.

Now it works as expected, and with high improve in speed and resources.

Leave a Reply

Your email address will not be published. Required fields are marked *