Re: [RFC] Context Managers
| From: | Larry Garfield | Date: | Sun, 09 Nov 2025 15:07:40 +0000 |
| Subject: | Re: [RFC] Context Managers | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-129165@lists.php.net to get a copy of this message | ||
On Wed, Nov 5, 2025, at 5:58 PM, Bob Weinand wrote:
> You are right, I missed that there's an extra layer of nesting inside this.
> I think the DatabaseTransaction example put me on the wrong thought path
> because it just returned the connection it came from instead of a
> dedicated nested Transaction object. (The enterContext method in that
> example ought to include a startTransaction call.)
>
> However, I still think the proposed approach is dangerous with respect
> to forgetting the exitContext() call. When using manual handling. But
> yes, I agree, that's a much more manageable concern.
> And the onus of handling duplicate enterContext() and multiple
> exitContext() calls still lies on the implementer. The RFC does zero
> effort at addressing this.
>
> Thanks,
> Bob
Bob, you seem to be focused on the "manual call" case. That... is not a case that exists.
I cannot think of any situation where a user creates a context manager and then calls enter/exit
context themselves that isn't a "stop that, you're doing it wrong" situation.
By the same token, you *can* implement Iterator and then call current() and next() and valid()
yourself... but odds are you're doing something wrong, and it's very easy to screw things
up if you call those methods in the wrong order or too many times or whatever. If you implement
Iterator, you're supposed to use it with foreach(). Doing anything else with it is "well
technically that maybe works, but please don't."
As Rowan noted, calling __construct() or __destruct() yourself is also possible, and can cause
things to go sideways, and if they do then it's your own damned fault, don't do that.
The same is true here. Someone manually calling enterContext and then not calling exitContext()
is... simply not a use case that matters, because there's no good reason to ever do so. The
only effort the RFC needs to make in this regard is say "don't do that."
--Larry Garfield