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
}