Api route pattern on the SlimPhp microframework?

后端 未结 2 750
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 23:42

Is there some pattern of routes and how to write the structure using SlimPhp?

Like, I made a api folder with a index.php to store ALL my routes:

$app         


        
2条回答
  •  醉话见心
    2020-12-22 00:18

    I usually have my own router before I involve Slim's router to determine which route to use based on the path after the domain:

    public/index.php

    chdir(dirname(__DIR__));
    
    require_once 'vendor/autoload.php';
    
    $app = new Slim\App;
    require 'app/routes/index.php';
    $app->run();
    

    app/routes/index.php

    $_url = parse_url($_SERVER['REQUEST_URI']);
    $_routes = explode('/',$_url['path']);
    $_baseRoute = $_routes[1];
    
    switch ($_baseRoute) {
        case 'api':
            $_routeFile = 'app/api/' . $_routes[2] . '.php';
            break;
    
        default:
            $_routeFile = 'app/routes/' . $_baseRoute . '.php';
            break;
    }
    
    if (file_exists($_routeFile)) {
        require $_routeFile;
    }
    else {
        die('Invalid API request');
    }
    

提交回复
热议问题