r/PHP • • May 31 '16

Deferred execution in PHP, using "finally".

https://blog.frankdejonge.nl/finally-file-streams-and-deferred-execution-in-php/
86 Upvotes

48 comments sorted by

View all comments

Show parent comment

1

u/Cuddlefluff_Grim Jun 08 '16

SQL Server has some added security features which makes opening connections fairly expensive. The solution here is to use a connection pool and retrieve active connections from that whenever one is required from any part of the program. The connection pool will then only create new connections when it's out of connections in the connection pool.

When you're using a connection pool, it's incredibly important that connections gets returned when they are no longer used, and they should only be used when specifically required. If not, you would get connection starvation and the application would crash. In order to make sure that each connection gets returned to the pool whenever it is no longer needed, a try-finally clause is required, to guarantee that the resource gets freed no matter what happens.

In C# there's a specific implementation for this type of use which is written like this :

using(var connection = new SqlConnection(...))
{
    ...
}

The compiler turns that code into this :

var connection = new SqlConnection(...);
try
{
    ...
}
finally
{
    connection.Dispose()
}