Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

object persistence in php

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...