I am fairly new to web programming, I have mainly used java to create desktop applications in the past.
I'm trying to figure out how to create persistent objects in php. Maybe persistent isn't the right word, I don't want the object to be unique to each client, like i would get by serializing it in a session variable. I want the object to be created on the server and have that same object be accessible at all times. The object would query the database and store some data. This way, each page load, the php code would get that data from the same persistent object rather than having to query the database each time.
I am currently using the singleton pattern for object creation because my initial understanding was that it would allow me to accomplish what i want. Part of the object is an array, and when i execute a php page that adds a value to the array, and access that value on the same page, its fine. However when i add a value to the array and then load another page that accesses the value, the array is back to being empty.
Is this possible? Am i overreacting in thinking that querying the database so much is bad? There will at times be as many as 20 users requesting data during any one second, and i feel like thats ridiculous to query the db each time.
Thanks
PHP does not have the concept of persistence as Java does: the JVM allows for Java applications to persist in memory between HTTP requests; the webserver forks a new PHP process every time a new HTTP request is served so an object's static variables will not persist data for you between requests.
Use a database to store persistent data. Web programming focuses on concurrency, so you shouldn't worry about database queries - 20 a second is few. If you reach the limits of your database you have the options to add a caching layer or "scale out" hardware by adding read-only slaves.
Usually you get your persistence by using the database. If that's a bottleneck you start caching data, for example in memcached or maybe a local file with a serialized array on your webserver.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With