Last active
December 22, 2015 08:49
-
-
Save minodisk/cbba583dd4b3c7f58ace to your computer and use it in GitHub Desktop.
CRUDなアプリケーションの簡易ルーティング
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Options +FollowSymLinks | |
| IndexIgnore */* | |
| RewriteEngine On | |
| RewriteCond %{REQUEST_FILENAME} !-f | |
| RewriteCond %{REQUEST_FILENAME} !-d | |
| RewriteRule . index.php |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * ルーティングの定義です。 | |
| */ | |
| $routes = array( | |
| post => array( | |
| '/^\/shop\/posts\/?$/' => 'create_shop_posts' | |
| ) | |
| , get => array( | |
| '/^\/search\/(.*)\/?$/' => 'read_search' | |
| , '/^\/shop\/posts\/?$/' => 'read_shop_posts' | |
| ) | |
| , put => array( | |
| '/^\/shop\/posts\/?$/' => 'update_shop_posts' | |
| ) | |
| ); | |
| /** | |
| * リクエストURIに基づいてルーティングします。 | |
| * 定義されていないルートでリクエストされた場合はエラーを出力します。 | |
| */ | |
| function route() { | |
| global $routes; | |
| $method = strtolower($_SERVER['REQUEST_METHOD']); | |
| $uri = preg_replace('/^\/api(\/.*)/', '$1', $_SERVER['REQUEST_URI']); | |
| foreach ($routes[$method] as $reg_exp => $method_name) { | |
| if (preg_match($reg_exp, $uri, $matches)) { | |
| call_user_func_array($method_name, $matches); | |
| return; | |
| } | |
| } | |
| error(); | |
| } | |
| /** | |
| * HTTPコードと共にエラーを出力します。 | |
| */ | |
| function error() { | |
| header('Content-Type: text/plain; charset=utf-8'); | |
| header(':', true, 400); | |
| echo 'HTTP/1.0 400 Bad Request'; | |
| exit(); | |
| } | |
| route(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment