I have a class with methodA, which has existing structure as following
function methodA() {
$providers = $this->getFirstSetOfProviders();
foreach ($providers as $provider) {
try {
$this->method1($provider);
} catch ( Exception $e ) {
// exception handling
}
}
$providers = $this->getSecondSetOfProviders();
foreach ($providers as $provider) {
try {
$this->method2($provider);
} catch ( Exception $e ) {
// exception handling
}
}
}
The content for the catch clauses are identical. Is there some way to organize the code to avoid repeating the structure of try/catch nested in a foreach loop? Conceptually, I am trying to do
function methodA() {
foreach ($providers as $provider) {
$method1 = function($provider) {
$this->method1($provider);
}
$this->withTryCatch($method1);
}
...
}
function withTryCatch($method) {
try {
$method; // invoke this method somehow
} catch (Exception $e) {
// exception handling
}
}
This looks similar to the Code sandwich, but I am not sure how to proceed in php.
UPDATE: The try/catch is nested inside the foreach loop so that when an exception is thrown, it's handled and the execution continues to the next iteration in the loop instead of terminating the loop.