LoginSignup
31
43

More than 5 years have passed since last update.

生のPHPでREST APIっぽいルーティングを作る

Last updated at Posted at 2017-07-19

生のPHPでREST APIっぽいルーティングを作る

REST APIを作るときは、通常、Lumen: https://lumen.laravel.com/ などのマイクロフレームワークや、
普通のフレームワークを使うのが便利ですが、今回は生のPHPのみでREST APIのサンプルを作成してみます。

以下、説明のためにtestディレクトリにルーティングのファイルを置くと仮定します。
適宜、読み替えてください。

サーバーの設定

まず、ファイル名の指定なしでアクセスするために、Rewrite設定をします。

Apacheを使っている場合は、testディレクトリの中に以下のようなファイルを置きます。

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

nginxを使っている場合は、以下のような設定をファイルに追記します。

location /test {
  try_files $uri $uri/ /test/index.php?$query_string;
}

ルーティングのソースコード

index.php
<?php
preg_match('|' . dirname($_SERVER['SCRIPT_NAME']) . '/([\w%/]*)|', $_SERVER['REQUEST_URI'], $matches);
$paths = explode('/', $matches[1]);
$id = isset($paths[1]) ? htmlspecialchars($paths[1]) : null;
switch (strtolower($_SERVER['REQUEST_METHOD']) . ':' . $paths[0]) {
case 'get:user':
  if ($id) echo "ユーザー #{$id} 取得";
  else echo 'ユーザー 一覧';
  break;
case 'post:user':
  echo 'ユーザー 登録';
  break;
case 'put:user':
  echo "ユーザー #{$id} 更新";
  break;
case 'delete:user':
  echo "ユーザー #{$id} 削除";
  break;
}

テスト

ユーザー一覧: http://example.com/test/user (GET)
ID #1 のユーザー取得: http://example.com/test/user/1 (GET)
ユーザー登録: http://example.com/test/user (POST)
ID #1 のユーザー更新: http://example.com/test/user/1 (PUT)
ID #1 のユーザー削除: http://example.com/test/user/1 (DELETE)

Chrome拡張のPostmanなどで確認すると楽です。

31
43
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
31
43