php global variable
Well, I'm relatively new to php but have worked on web apps previously. I'm currently writing code in php and running Apache httpd. The DB 开发者_StackOverflow中文版I'm using is PostgreSql.
This web app will connect to DB very frequently. For that reason I'm looking for something that enables me not to initiate connection every time a user accessed a page.
Is it possible in php to set a variable that is same for all users.
For eg. I want to save a DB connection object in a variable and use it whenever I want.
That variable will go out of scope when Apache Server stops.
Smarmy answer first. Yes you can. It's called the database ;-)
Seriously though, Apache + PHP (without anything else) is not the best option if you're trying to persist values across requests. Normally, if that type of functionality is needed, it is done through either a hard file or a database connection which is refreshed every time a request is triggered. Obviously neither of those are sufficient to persist an entirely separate connection.
The general rule is one request one connection. There are ways to persist connections so that this number is lowered but pg_connect
which was supposed to be a canonical way to approach this problem, seems to be incredibly broken. You may wish to look into pgbouncer
or pgpool
instead. I don't know how the PDO driver handles ATTR_PERSISTENT
for Postgre.
The need to connect to a DB frequently is a common feature of web applications written in PHP, which is why the oci_pconnect() function uses a persistent cache of connections that can be re-used across different script/page requests (so the DB connection overhead is paid only once per Apache child or PHP process) - see PHP DB connection handling
Is there any particular reason why you want to do the work of managing a DB connection pool yourself? If you're absolutely Hell-bent on this idea, then you could use something like a shared memory segment to store data objects that are to be shared across processes - but then you need a mutex system to avoid death by race condition when modifying the shared data, a "watchdog" to clean things up when a process dies without properly releasing a mutex, etc.
精彩评论