Skip to content

Instantly share code, notes, and snippets.

@minodisk
Last active December 22, 2015 08:49
Show Gist options
  • Select an option

  • Save minodisk/cbba583dd4b3c7f58ace to your computer and use it in GitHub Desktop.

Select an option

Save minodisk/cbba583dd4b3c7f58ace to your computer and use it in GitHub Desktop.
CRUDなアプリケーションの簡易ルーティング
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
/**
* ルーティングの定義です。
*/
$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