On Tue, 1 Oct 2024, at 19:29, Larry Garfield wrote:
> I would have said with() would be neat in PHP. :-)

I have been considering for a while proposing Context Managers [Python's 
with(), not to be confused with VisualBasic & JavaScript unrelated feature with 
the same keyword].

My primary example use case is safe database transactions, which I've seen 
implemented in PHP in two ways:

1) Callback style, where the code to run in a transaction has to be wrapped in 
a function, usually an anonymous closure. This is often cited as a use case for 
implicit capture in closures, but even with that it adds a layer of 
indirection, and changes the meaning of "return" and "yield" inside the wrapped 
block.

2) "Resource Acquisition Is Initialization" style, where the destructor rolls 
back the transaction if it hasn't been committed or rolled back manually. This 
requires fewer changes to the wrapped code, but as Arnaud points out, it's not 
100% reliable / predictable in PHP, due to details of the GC.

Context Managers present a third option, where the code in the transaction 
remains a normal sequence of statements, but there is a more explicit guarantee 
about what will happen when the with{} block is exited. The Python design 
document has interesting background on what they included and excluded: 
https://peps.python.org/pep-0343/

C#'s "using statement" is similar, but explicitly designed for ensuring the 
correct "disposal" of an object rather than hooking entry to and exit from a 
"context": 
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/using

Regards,
-- 
Rowan Tommins
[IMSoP]

Reply via email to