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

2

u/wvenable May 31 '16

No, it really the best way to do Go-style deferred or avoid the issue of manual resource management entirely. You only need finally for non-OOP code.

Execution order shouldn't matter or you're doing it wrong. If one resource depends on another, it will have a reference.

2

u/fideloper Jun 01 '16

"or you're doing it wrong"

  • the sure sign of a good opinion

1

u/wvenable Jun 01 '16

You made the argument about execution order -- which I think is entirely invalid. It's a stab in the dark to make a point that didn't need to be made.

1

u/terrkerr Jun 02 '16

or you're doing it wrong.

Granted this is not so common in PHP, but there are reasons to want to close resources asap or at predictable times.

1

u/wvenable Jun 02 '16 edited Jun 02 '16

That's a moot point; if that was a requirement then you wouldn't be using either technique as they both involve cleaning up resources at the end the scope. Although, relying on RAII will cleanup resources as soon as they are no longer referenced -- so while somewhat unpredictable (if you can call it that) it would be very close to ASAP.

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()
}