LoginSignup
2
3

More than 5 years have passed since last update.

php でお手軽ルーティング

Posted at

シンプルなルーティングルールならライブラリなしで簡単にできます。

<?php

try {
    routing();
} catch (\Throwable $e) {
    // なんかエラー処理
}
exit();

function routing()
{
    //parse_url() は相対パスを渡すと一部のパターンでおかしな動きをするので、このようにURL全体を渡している
    // http://koseki.hatenablog.com/entry/20120210/phpuri
    $request_url = parse_url('https://example.com' . $_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $request_method = strtolower($_SERVER['REQUEST_METHOD']);

    $route_map = [
        '/v1/endpoint1' => ['get'  => function() { endpoint1();}],
        '/v1/endpoint2' => ['post' => function() { endpoint2();}],
    ];

    if (isset($route_map[$request_url][$request_method])) {
        $route_map[$request_url][$request_method]();
    } else {
        // ここは本当は throw したほうが取扱やすいと思う
        http_response_code(404);
        echo '404';
    }
}


function endpoint1() {
    echo 'endpoint1';
}

function endpoint2() {
    echo 'endpoint2';
}

あとは以下のような形で built in server を使えば動作確認も簡単にできます。

php -S localhost:12345 index.php

超簡単!

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3