0

When creating an api each valid URI is mapped to an action. This action can be a specific function call or can set some parameters passed to a generic function.

My question is how or what are the good method to map an uri such as /auth/create to the right action.

To illustrate my attempts:

I thought about naming a function the same as a the URI replacing the / with Z to directly call the function by its name. I could basically simply execute the $request_uri directly without testing.

// from $request_uri = '/auth/create' I make;
$request_uri ='ZauthZcreate';

function ZauthZcreate($email, $password) {
  echo "i've been called as expected \n";
}
$request_uri($_GET[email],$_GET[password]);

but it wouldn't work with something like /user/123123. I am trying to avoid falling in an endless cascade of if-else.

EDIT

I've iterated on this concept and found another solution:

$request_uri    = '/api/auth/login';
$request_path   = ltrim($request_uri,'/');
$request        = explode('/', $request_path);

// begin point for api
if($method = array_shift($request)) {
  if ($method == 'api') {
    $method($request);
  }
}

function api($request) {
  $method = __FUNCTION__.'_'.array_shift($request);
  if(is_callable($method)) {
    $method($request);
  }
}

// In a dedicated file for the scope auth

function api_auth($request) {
  $method = __FUNCTION__.'_'.array_shift($request);
  if(is_callable($method)) {
    $method($request);
  }
}

function api_auth_login($request) {
  // api end point implementation here
}
function api_auth_create($request) {
  // api end point implementation here
}
Nicolas Manzini
  • 8,379
  • 6
  • 63
  • 81

1 Answers1

0

I wouldn't use those Z's, that's going to be needlessly difficult to read. In your above example you could do the same thing with just AuthCreate. You could also do this with OO design by making a base class for your main verbs (like Auth) and then having them declare their member functions.

Ultimately you wont want to resolve this with if/else blocks, but rather parse each part of the URI and see if a function in the right namespace exists, and once it doesnt start using your slashes as inputs (for your example above with /user/123123).

It might also do you well to look at how other REST API's are structured, because this is something of a solved problem

DaOgre
  • 2,080
  • 16
  • 25