Here's a simplified way to route request paths to classes. This example assumes your base path is /app and you have a sub-folder called /classes. The class name and file name must match for this to work.
Example request:
curl -X POST http://localhost/api/user/123
Example route:
File....: /app/classes/api/User.php Class...: new User() Action..: postAction( $arg1 = 123 )
...
// default route $base = rtrim( str_replace( '\\', '/', __DIR__.'/app' ), '/' ); $area = 'api'; // area (/api, /test, etc.) $class = 'home'; // class name (Home.php -> new Home(), etc.) // parse request $verb = strtolower( @$_SERVER['REQUEST_METHOD'] ); $path = parse_url( @$_SERVER['REQUEST_URI'], PHP_URL_PATH ); $args = explode( '/', trim( $path, '/' ) ); // extract area/class from request path if( count( $args ) ) { $area = array_shift( $args ); } if( count( $args ) ) { $class = array_shift( $args ); } // finalize class name and file path $class = str_replace( ' ', '', ucwords( str_replace( '-', ' ', $class ) ) ); $file = $base .'/classes/'. $area .'/'. $class.'.php'; $output = null; // load/execute class if( is_file( $file ) ) { include_once( $file ); if( class_exists( $class ) ) { $callable = [ new $class(), $verb.'Action' ]; if( is_callable( $callable ) ) { $output = call_user_func_array( $callable, $args ); } } } // send response output... if( is_null( $output ) === false ) { // ... } else { // handle error } exit;