PHP - pattern to reuse same behavior across class methods

59 Views Asked by At

I'm writing a service class that wraps up calls to some api endpoint using Guzzle.

I ended up writing those methods with basically identical Guzzle exception handling, i.e.:

class ServiceClass {

    public function getMethod(){
        try {
            $response = $guzzleClient->get("some/url");
            // some business logic
            return $data;
        }
        catch(ClientException $e) {
            // handle exception
        }
        catch(RequestException $e) {
            // handle exception
        }
    }

    public function postMethod(){
        try {
            $response = $guzzleClient->post("another/url", [/* some data */]);
            // other business logic
            return;
        }
        catch(ClientException $e) {
            // handle exception
        }
        catch(RequestException $e) {
            // handle exception
        }
    }
}

Since every endpoint behave the same despite being a POST or a GET, i.e. in case of errors they returns the exact same response body structure (e.g. errors array), I'm wondering if there is a way to kinda "extends" every methods to reuse the same try-catch logic and isolate relevant individual business logics.

0

There are 0 best solutions below