Connection pooling in PHP

There is no connection pooling in php.

mysql_pconnect and connection pooling are two different things. There are many problems connected with mysql_pconnect and first we should read the manual and carefully use it, but this is not connection pooling.

Connection pooling is a technique that the application server manages the connections. Then the app requires a connection from the application server and the server returns a reference.

Apache releases all resources when the request ends for the current reques. We can use mysql_pconnect but we are limited with that function and we must be very careful. Other choice is to use singleton pattern, but none of this is pooling.

When a PHP file finishes executing all it's state is killed so there's no way (in PHP code) to do connection pooling. Instead you have to rely on extensions.

You can mysql_pconnect so that your connections won't get closed after the page finishes, that way they get reused in the next request.

This might be all that you need but this isn't the same as connection pooling as there's no way to specify the number of connections to maintain opened.

Persistent connections are nothing like connection pooling. A persistent connection in php will only be reused if you make multiple db connects within the same request/script execution context. In most typical web dev scenarios you'll max out your connections way faster if you use mysql_pconnect because your script will have no way to get a reference to any open connections on your next request. The best way to use db connections in php is to make a singleton instance of a db object so that the connection is reused within the context of your script execution. This still incurs at least 1 db connect per request, but it's better than making multiple db connects per reqeust.

There is no real db connection pooling in php due to the nature of php. Php is not an application server that can sit there in between requests and manage references to a pool of open connections, at least not without some kind of major hack. I think in theory you could write an app server in php and run it as a commandline script that would just sit there in the background and keep a bunch of db connections open and pass references to them to your other scripts, but I don't know if that would be possible in practice, how you'd pass the references from your commandline script to other scripts, and I sort of doubt it would perform well even if you could pull it off. Anyway that's mostly speculation. I did just notice the link someone else posted to an apache module to allow connection pooling for prefork servers such as php. Looks interesting:

Posted in PHP | Tagged , , | Comments Off

Comments are closed.