PHP code example of fostam / simplerouter

1. Go to this page and download the library: Download fostam/simplerouter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fostam / simplerouter example snippets




ostam\SimpleRouter\Response;
use Fostam\SimpleRouter\Router;
use Fostam\SimpleRouter\Http;
use Fostam\SimpleRouter\Exception\InternalApiException;
use Fostam\SimpleRouter\Exception\UserApiException;

$router = new Router();
try {
    // all URLs must be prefixed with this string
    $router->setOption(Router::OPT_REQUEST_PATH_PREFIX, '/myproject/api');

    // send permissive cross origin resource sharing headers
    $router->setOption(Router::OPT_CORS_PERMISSIVE, true);
    
    // by default, send the response with application/json content type
    $router->setOption(Router::OPT_RESPONSE_TYPE_DEFAULT, Response::TYPE_JSON);

    // routes
    $router->createRoute('/users', Http::METHOD_GET, \MyProject\GetUsers::class);
    $router->createRoute('/users/{id}', Http::METHOD_GET, \MyProject\GetUsers::class);
    $router->createRoute('/users', Http::METHOD_POST, \MyProject\CreateUser::class);

    // resolve
    $router->resolve();
}
catch (UserApiException $e) {
    // error messages are automatically passed back as JSON
}
catch (InternalApiException $e) {
    // a generic error message is passed back as JSON; trigger the actual errors
    // (e.g. a failed database query) that should not be publicly visible, but
    // logged internally
    error_log($e);
}

$router->sendResult();

class GetUsers extends Processor {
    public function execute() {
        $userID = $this->getPathParam('id');
            
        if (!is_numeric($userID)) {
            throw new UserApiException('userID must be a number', Http::CODE_BAD_REQUEST, $e);
        }

        try {
            $data = $this->myUserModel->getUser(intval($userID));
        } catch (\Exception $e) {
            throw new InternalApiException("error getting data for user {$userID}", Http::CODE_INTERNAL_SERVER_ERROR, $e);
        }

        $this->setResponseData(
            [
                'data' => $data
            ]
        );
    }
}

class CreateUser extends Processor {
    public function execute() {
        $data = $this->getJSONPostData();
        if (!isset($data['name'])) {
            throw new UserApiException("parameter 'name' is missing");
        }

        try {
            $userID = $this->myUserModel->createUser($data);
        } catch (\Exception $e) {
            throw new InternalApiException("error creating user", Http::CODE_INTERNAL_SERVER_ERROR, $e);
        }
                
        // send "201 Created"
        $this->setResponseCode(Http::CODE_CREATED);
        
        // send the location of the new object as header
        // here: 'Location: /myproject/api/users/123' (for $userID=123)
        $this->getResponseObject()->setLocationPath($this->getPath() . '/' . $userID);
    }
}

$router->createRoute('/test/{id}/user/{name}', Http::METHOD_GET, Test::class);
$router->resolve('/test/123/user/john', Http::METHOD_GET);

array(2) {
  'id' =>
  string(3) "123"
  'name' =>
  string(4) "john"
}

array(2) {
  'id' =>
  int(123)
  'name' =>
  string(4) "john"
}

$router->setOption(Router::OPT_REQUEST_PATH_PREFIX, '/test/api');
...
$this->getResponseObject->setLocationPath('/users');
...
Location: /test/api/users

addResponseData('data.user.name', 'John')