
As one of my projects has been growing in complexity, I’ve noticed that building a PHP file per REST Request is now growing out of control and I’m ending up with alot of PHP files and thus, this is becoming somewhat unmanageable. With the project I have started to notice how WordPress must work with it’s REST API based on my work with Angular and the .htaccess configuration needed for Apache2 to get it working.
So, my plan is that I want 1 PHP file which services all my REST functions, i.e. An Actual REST API! Without also creating hundreds of individual PHP files as it was starting to get a bit complicated anyway. Later we’ll migrate things but for now, let’s just get our own function working. First, I create the directory under demo’s for api and then I write a .htaccess file within that directory for this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /demos/api
RewriteRule ^functions\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . functions.php [L]
</IfModule>
Now with this, it tells Apache2 to forward any request for an unknown file in this directory to /demos/api/functions.php. So now I just need to create my functions.php and as a simple first pass test I program it to just echo “Here”:
<?php
echo "Here";
?>
And hey presto:

Great, so any function will be identified by the “php” file that is requested to the api directory. i.e. since my jquery put in a POST request for newuser.php, then that is the function we’re calling.
To figure out our function, first we can use $_SERVER[‘REQUEST_URI’] and then we split the string and take the last string where we split by “/” and then do this again but take the first string and split by “.” to get our function name.
Now the POST data should maintain itself between function calls so alls I need to do next is actually call the function. But this article seemed to provide some good guidance for me:
And finally I end up with something like this:
<?php
$names = end(explode("/", $_SERVER['REQUEST_URI']));
$function = reset(explode(".", $names));
class RESTAPI {
public function caller($to_call) {
if (is_callable([$this, $to_call])) {
$this->$to_call();
}
}
public function newuser() {
echo "In function - create user";
echo $_POST['whoami'];
}
}
$dcObject = new RESTAPI();
$dcObject->caller($function);
?>
And my function call returns:

Yay! It worked, now I can add functions to this class object and then call them without having to create a PHP file per REST request.