On Tue, Oct 1, 2024, at 2:06 PM, Rowan Tommins [IMSoP] wrote:
> 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]

I would support having Python-esque context managers in PHP, and would be happy 
to help make it happen (if research and English writing would be useful to 
whoever is doing the implementation).

--Larry Garfield

Reply via email to