0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

生PHPでAPIルーティング, リフレクションで動的にクラスメソッド実行

Posted at

生PHPで、APIルーティング

要件
api/class/methodでのAPIリクエストを想定。
リフレクションで動的に実行する。

php index.php
<?php
// var_dump($script_name['SCRIPT_NAME']); => /api/index.php
// var_dump($script_name['REQUEST_URI']); => /api/class/method

// URI`api/hoge/fuga?aa=1`から、`hoge/fuga`を取得
// デリミタは、URIの`/`と被らないように指定
$delimiter = '~';
$pattern = $delimiter .dirname($_SERVER["SCRIPT_NAME"]).'/([\w]*)/([\w]*)' . $delimiter;
$result = preg_match($pattern, $_SERVER["REQUEST_URI"], $matches);

// 正規表現より、`Index Out Of Bounds`は起きないはず
$paths = explode('/', $matches[1]);
$class = $paths[1];
$method = $paths[2];

// 今回は要件より、リクエストメソッドは見ない
// $_SERVER['REQUEST_METHOD'];
$class_file = __DIR__ . '/{$class}.php';
if(file_exists($class_file)){
    require_once $class_file;

    try{
        $reflection = new ReflectionClass($class);
    
        // 実行可能なクラスメソッドか?
        if($reflection->isInstantiable()
            && $reflection->hasMethod($method)
            && $reflection->getMethod($method)->isPublic()
            && $reflection->getMethod('__construct')->isPublic())
        {
            $controller = $o_reflection->newInstance();
            // $o_controller->

            echo '{"result":"ok"}';
        }
    
    }catch(ReflectionException $e){
        var_dump($e);
    }
    
}else{
    http_response_code(404);
    include './404.php';
    exit;
}

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

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?