mercredi 14 septembre 2022

Is it possible to make methods behave based on the caller without checking each possibility?

I have a small backend to get data from an API. I'm using only one class to manage multiple API endpoints (JWT token and 2 other endpoints) and good old Curl to build the requests. Currently i'm using a private method (buildCurl) that behaves based on another internal method that calls it -currently three, corresponding to the endpoints-. the callers pass their name to buildCurl so it can check and build the necessary request accordingly.

It works fine but i feel like i'm doing something fundamentally wrong from the design perspective or there are more elegant solutions to this, specially if the number of endpoints increases.

What i can see: my first guess would be to make one class for each endpoint, but that would generate a lot of code duplication. Another one would be to make my current class a parent class of my endpoints (inheritance) and make buildCurl polymorphic (but one class for each endpoint would still be necessary).

Here's the code:

class ApiRequestManager {
...
  // One endpoint
  public function getDataCpf(string $cpf) {
    ...
    // Get the curl resource. Give the current function/method name to buildCurl.
    $curl = $this->buildCurl($authString, $requestParam, __FUNCTION__);
    ...
    return $this->getResponse($curl, ...);
  }
  private function buildCurl($authString, $parameters, $methodName) {
    // Options common to all cases
    $options = [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_FOLLOWLOCATION => true,
      ...
    ];

    if($methodName === 'getToken') {
      $options[CURLOPT_URL] = $this->apiConfig['serverUrl'] . $this->apiConfig['authTokenUrl'];
      ...
    } elseif($methodName === 'getDataCpf') {
      ...
    } elseif(...) {
      ...
    }
  }
  ...
}

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire