Subject says it all.
I want to make a small "ScopeGuard" library for exception-safe
transactions, like the following:
$scope = new ScopeGuard;
$scope->onSucces(function() { logTransactionOne(); });
$scope->onFailure(function() { rollbackTransationOne(); });
doTransactionOne();
$scope->onSuccess(function() { logTransactionTwo(); });
$scope->onFailure(function() { rollbackTransactionTwo(); });
$scope->onFailure(function() { logFailureOfTransactionTwo(); });
doTransactionTwo();
// ... Three Four etc...
So if an exception is thrown the attached onFailure callbacks will be
executed, if the scope is exited through a return however the success
callbacks will be executed.
This requires me to know in ScopeGuard::__destruct() if the scope was
left normally or due to an exception.
The code in https://github.com/php/php-src/blob/master/Zend/zend_objects.c#L135
(line 135) seems to prevent me from knowing that information, because
the exception is temporarily removed from the globals and put in a
local variable.
Is there any way to detect if an exception is currently in flight?
(I've asked this same question on SO last week:
http://stackoverflow.com/questions/33199997/in-destruct-how-can-you-see-if-an-exception-is-currently-in-flight)
Subject says it all.
I want to make a small "ScopeGuard" library for exception-safe
transactions, like the following:$scope = new ScopeGuard; $scope->onSucces(function() { logTransactionOne(); }); $scope->onFailure(function() { rollbackTransationOne(); }); doTransactionOne(); $scope->onSuccess(function() { logTransactionTwo(); }); $scope->onFailure(function() { rollbackTransactionTwo(); }); $scope->onFailure(function() { logFailureOfTransactionTwo(); }); doTransactionTwo(); // ... Three Four etc...
So if an exception is thrown the attached onFailure callbacks will be
executed, if the scope is exited through a return however the success
callbacks will be executed.
The way to do this is by marking the success in an explicit way. See
http://slides.com/johannes4321/froscon15/#/4 and
http://slides.com/johannes4321/froscon15/#/6
With your attempt you can only handle abortion via exception. With a
pattern like shown in my slides you can also handle cases where you
"return" early nicely.
johannes