Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9186869
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T19:38:09+00:00 2026-06-17T19:38:09+00:00

I have a class with methodA, which has existing structure as following function methodA()

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T19:38:10+00:00Added an answer on June 17, 2026 at 7:38 pm

    The nice thing about Exceptions is that they are objects that can be passed around like any others. So you can remove the duplicate code (except the basic boilerplate) without changing much:

    foreach ($providers as $provider) {
        try {
          $this->method1($provider);
        } catch ( Exception $e ) {
          $this->handleException($e);
        }
    }
    

    Note: If you also need some context within the exception handling (i.e. $provider), just give handleException() more parameters.

    Part 2: Refactoring the whole method

    You wanted to know how to further remove duplication. I don’t know if this makes sense in your actual code, it could as well be over-engineering. You will have to decide that by yourself. The following is an implementation of the Template Method pattern. Forgive the crude naming but I tried to follow your example and I have no idea what you are doing.

    abstract class ClassThatDoesThingsWithProviders
    {
        public function methodA($providers)
        {
            foreach($provicers as $provider) {
                try {
                    $this->methodThatActuallyDoesSomethingWithProvider($provider);
                } catch(Exception $e) {
                    $this->handleException($e);
                }
            }
        }
        protected function handleException(Exception $e)
        {
            // handle exception
        }
        abstract protected function methodThatActuallyDoesSomethingWithProvider($provider);
    }
    class ClassThatDoesThing1WithProviders extends ClassThatDoesThingsWithProviders
    {
        protected function methodThatActuallyDoesSomethingWithProvider($provider)
        {
            // this is your method1()
        }
    }
    class ClassThatDoesThing2WithProviders extends ClassThatDoesThingsWithProviders
    {
        protected function methodThatActuallyDoesSomethingWithProvider($provider)
        {
            // this is your method2()
        }
    }
    
    class YourOriginalClass
    {
        protected $thingsdoer1;
        protected $thingsdoer2;
    
        public function __construct()
        {
            $this->thingsdoer1 = new ClassThatDoesThing1WithProviders;
            $this->thingsdoer2 = new ClassThatDoesThing2WithProviders;
        }
        public function methodA()
        {
            $this->thingsdoer1->methodA($this->getFirstSetOfProviders());
            $this->thingsdoer2->methodA($this->getSecondSetOfProviders());
        }
    }
    

    You could easily make an array out of thingsdoer1 and thingsdoer2 and maybe abstract getFirstSetOfProviders and getSecondSetOfProviders alongside. Also I don’t know what the actual method1 and method2 implementations depend on, maybe you cannot extract them like that without breaking cohesion.

    But as I don’t know your real code and what you are doing I cannot recommend a concrete strategy, regard my example above as a starting point.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this form which relates to an object of class Film, which has
I have a complex django object, which has properties of other class types. This
I have a class with static method which has a local static variable. I
Imagine you have class A which has code which runs as method M. And
I have a class that has an output() method which returns a matplotlib Figure
I have a class called Property which has nothing but get -methods. All the
I have a controller which has a method called history class UsersController < ApplicationController
I have an object class called BOM. It has a method, getChildItem() which returns
In some C++/CLI code I have a native class which has a factory method
I have an existing list instance, which in live code has references throughout. When

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.