phpmodelstatepersistent-data

Models with persistent state between HTTP requests


I want to create a web application with a model that persists between HTTP requests. From what I understand languages like PHP treat each HTTP request as a brand new connection except for some global variables like SESSION; so each time the user changes pages all my PHP classes are loaded into memory again (and each AJAX request does this too) - requiring me to build from the database each time.

Am I mistaken or am I trying to make a circle fit in a square? Memcached seems to be a good solution for keeping my model in memory between page requests but it still needs to load the cache. PHP CLI seemed promising but after looking into it more it seemed like it would be more trouble than it was worth. Any suggestions?


Solution

  • You should avoid requiring a persistent state in your web application; HTTP is stateless and you need to design your business logic around that. Also, PHP isn't very memory-leak safe since it isn't meant to act as a daemon or run for extended periods. You shouldn't be maintaining a database of information in PHP variables either. You can cache expensive query results in memcache and retrieve them with very little latency.

    You can serialize your model, store it in a session (or memcache), and deserialize it on the next request in order to keep relevant variables within scope between requests. If you share a bit more about the specifics of your application, perhaps we can help you figure out the best way to handle this.