Ground Sunlight

Windowsで作る - PHPプログラミングの開発環境

ユーザ用ツール

サイト用ツール


basic-library:fast-route:1.3

差分

このページの2つのバージョン間の差分を表示します。

この比較画面にリンクする

両方とも前のリビジョン 前のリビジョン
次のリビジョン
前のリビジョン
basic-library:fast-route:1.3 [2020/03/22 14:49]
y2sunlight [テストプログラム]
basic-library:fast-route:1.3 [2020/07/14 15:36]
y2sunlight [テストプログラム]
行 1: 行 1:
-> 投稿中です。しばらくお待ちください。 +====== リクエストルーター - FastRoute ======
- +
----- +
- +
-====== リクエストルーター - fast-route ======+
 Version 1.3 ([[https://github.com/nikic/FastRoute/blob/master/LICENSE|BSD 3-Clause License]]) Version 1.3 ([[https://github.com/nikic/FastRoute/blob/master/LICENSE|BSD 3-Clause License]])
  
行 11: 行 7:
  
 関連記事 関連記事
-  * [[basic-library:project|プロジェクトの作成 - apricot]]+  * [[basic-library:project|プロジェクトの作成 - Apricot (α版)]]
   * [[basic-library:phpdotenv:4.1|環境変数 - phpdotenv]]   * [[basic-library:phpdotenv:4.1|環境変数 - phpdotenv]]
   * [[basic-library:monolog:2.0|ログ出力 - monolog]]   * [[basic-library:monolog:2.0|ログ出力 - monolog]]
   * [[basic-library:idiorm:1.5|ORマッパー - Idiorm]]   * [[basic-library:idiorm:1.5|ORマッパー - Idiorm]]
   * [[basic-library:bladeone:3.37|テンプレートエンジン - BladeOne]]   * [[basic-library:bladeone:3.37|テンプレートエンジン - BladeOne]]
-  * リクエストルーター - fast-route +  * リクエストルーター - FastRoute 
-  * [[basic-library:whoops:2.7|エラーハンドラー - whoops]]+  * [[basic-library:league-container:3.3|DIコンテナー League/Container]] 
 +  * [[basic-library:valitron:1.4|バリデーター - Valitron]] 
 +  * [[basic-library:whoops:2.7|エラーハンドラー - Whoops]]
   * [[basic-library:php-debugbar:1.16|デバッグ出力 - php-debugbar]]   * [[basic-library:php-debugbar:1.16|デバッグ出力 - php-debugbar]]
  
行 30: 行 28:
 ---- ----
  
-===== fast-routeについて =====+===== FastRouteについて =====
  
->TODO:+FastRouteは、PHPコアの開発者の1人でもある [[https://nikic.github.io/aboutMe.html|Nikita]]氏が開発し、[[slim:top|Slim]] フレームワークにも採用されている高速なリクエストリーターです。興味のある方は、なぜ高速であるかを説明するNikita氏の[[http://nikic.github.io/2014/02/18/Fast-request-routing-using-regular-expressions.html|ブログ投稿]]もご覧下さい。 
 + 
 +リクエストリーターの選定に当たっては、最近の人気、実行速度、コードの品質から選びました。コードの品質については[[https://php.libhunt.com/|Awesome PHP]]を参考にしました。結果的に次の3つの候補から選びました: 
 + 
 +  * FastRoute --- https://github.com/nikic/FastRoute 
 +  * Klein --- https://github.com/klein/klein.php 
 +  * AltoRouter --- https://php.libhunt.com/altorouter-alternatives 
 + 
 +機能面を考えるとKleinとAltoRouterも捨てがたい魅力がありましたが、ORマッパーと同じく「兎に角シンプル」と「学習コストが少ない」そして何よりも''高速''という理由でFastRoute を採用することにしました。
  
 ===== インストール ===== ===== インストール =====
行 58: 行 64:
 パッケージの取得が終わると ''composer.json'' の ''require'' に以下が追加されます。 パッケージの取得が終わると ''composer.json'' の ''require'' に以下が追加されます。
  
-<code json composer.json>+<code javascript composer.json>
 { {
     "require": {     "require": {
行 70: 行 76:
 ===== テストプログラム ===== ===== テストプログラム =====
  
->TODO+テストフォルダ(''test\'')に フォルダ(''fast-route'') を作成し、そのフォルダに ''.htaccess'' と テストコード(''index.php'')を作成し実行します。''.htaccess''では rewrite を使って ''test\fast-route\'' 下への全ての(実在するディレクトリとファイを除く)リクエストをフロントプロセッサーである ''index.php'' に転送します。
  
-/test/fast-route/.htaccess +<code - .htaccess>
-<code>+
 <IfModule mod_rewrite.c> <IfModule mod_rewrite.c>
     RewriteEngine On     RewriteEngine On
行 82: 行 87:
 </code> </code>
  
-<code php /test/fast-route/index.php> +以下にテストコード('index.php')を示します。この例は、[[https://github.com/nikic/FastRoute|FastRoute]]サイトの''Usage''にある基本的な使用例を追加・修正したものです。本例の詳細はコード内のコメントをご覧ください。
-<?php+
  
 +大まかな流れは「''REQUEST_METHOD'' と ''REQUEST_URI'' でルーティングの定義を行い、それに従い ''dispatch()'' して制御をハンドラーに渡す」と言うものですが、この例ではハンドラーとして(名前のある)関数とクロージャ―(無名関数)を使いました。クラスのインスタンスメソッドの例は、[[apricot::top|Apricot]]をご覧下さい。
 +
 +<code php index.php>
 +<?php
 require __DIR__.'/../../vendor/autoload.php'; require __DIR__.'/../../vendor/autoload.php';
  
-$base_path = '/y2sunlight/apple/test/fast-route'; +// 自分(index.php)の場所を取得する 
-$routes = function(FastRoute\RouteCollector $r) use($base_path)+$base dirname($_SERVER['SCRIPT_NAME']); 
 +if (preg_match('/^[\\.\\\\]$/', $base)) $base=''; 
 + 
 +// ルーティング(コールバック関数)の定義 
 +// ルーティングは、get(path,handler),post(path,handler) の形式で指定する 
 +// (*1)handlerにcallable型を指定した 
 +// (*2)ベースとなるURLが同じなのでaddGroup()を使った) 
 +$routes = function (FastRoute\RouteCollector $r) use($base)
 { {
-    $r->addRoute('GET', $base_path.'/users', 'users'); +    $r->addGroup($basefunction (FastRoute\RouteCollector $r) use($base) 
-    $r->addRoute('GET', $base_path.'/user/{id:\d+}', 'user'); +    { 
-    $r->addRoute('GET', $base_path.'/articles/{id:\d+}[/{title}]', 'articles');+        // handlerに関数を指定する 
 +        $r->get('/users', 'users');          // 単純なルーティング 
 +        $r->get('/user/{id:\d+}', 'user');   // プレースフォルダ(名前:id) 
 +        $r->get('/articles/{id:\d+}[/{title}]', 'articles');  // 任意のプレースフォルダ
  
-    // Closure +        // handlerにクロージャを指定する 
-    $r->addRoute('GET', $base_path.'/', function() use($base_path){ +        $r->get('[/]', function() use($base
-        header("Location: " . $base_path.'/users');+        
 +            header("Location: " . $base.'/users'); 
 +        });
     });     });
 }; };
行 102: 行 122:
 $dispatcher = FastRoute\simpleDispatcher($routes); $dispatcher = FastRoute\simpleDispatcher($routes);
  
-// Fetch method and URI from somewhere+// dispatch()に与えるHTTPメソッドとURIを取得
 $httpMethod = $_SERVER['REQUEST_METHOD']; $httpMethod = $_SERVER['REQUEST_METHOD'];
 $uri = $_SERVER['REQUEST_URI']; $uri = $_SERVER['REQUEST_URI'];
  
-// Strip query string (?foo=barand decode URI +// dispatch()の妨げになるのでURIの中のクエリパラメータを除去する 
-if (false !== $pos = strpos($uri, '?')) { +// (クエリパラメータは、通常に$_GETで取得できる) 
-     $uri = substr($uri, 0, $pos);+if (false !== ($pos = strpos($uri, '?'))) { 
 +    $uri = substr($uri, 0, $pos);
 } }
 +// URIの中にクエリパラメータがあるかもしれないのでデコードする
 +// 例) /hoge/hoge/param/abc%20def
 $uri = rawurldecode($uri); $uri = rawurldecode($uri);
  
 +// URIのディスパッチ
 $routeInfo = $dispatcher->dispatch($httpMethod, $uri); $routeInfo = $dispatcher->dispatch($httpMethod, $uri);
-switch ($routeInfo[0]) {+switch ($routeInfo[0]) 
 +{
     case FastRoute\Dispatcher::NOT_FOUND:     case FastRoute\Dispatcher::NOT_FOUND:
-        // ... 404 Not Found+        // 404 Not Found
         break;         break;
 +
     case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:     case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
-        $allowedMethods = $routeInfo[1]; +        $allowedMethods = $routeInfo[1]; // 許可されているメソッド 
-        // ... 405 Method Not Allowed+        // 405 Method Not Allowed
         break;         break;
 +
     case FastRoute\Dispatcher::FOUND:     case FastRoute\Dispatcher::FOUND:
-        $handler = $routeInfo[1]; +        $handler = $routeInfo[1]; // ハンドラー 例)user 
-        $params = $routeInfo[2];+        $params = $routeInfo[2];  // パラメータハッシュ 例)['id'->123]
  
-        $handler($params);+        // ハンドラーを呼び出す 
 +        if (is_callable($handler)) 
 +        { 
 +            call_user_func_array($handler, $params); 
 +        }
         break;         break;
 } }
  
-// Action: users +// Handler: users 
-function users($vars)+function users()
 { {
     echo "users";     echo "users";
 } }
  
-// Action: user +// Handler: user 
-function user($vars)+function user(int $id)
 { {
-    echo "user({$vars['id']})";+    echo "user({$id})";
 } }
  
-// Action: articles +// Handler: articles 
-function articles($vars)+function articles(int $id, string $title=null)
 { {
-    $response = "articles({$vars['id']})"; +    echo "articles({$id}){$title}";
-    if(array_key_exists('title', $vars)) +
-    { +
-        $response.= $vars['title']; +
-    } +
-    echo $response;+
 } }
 </code> </code>
 +
 +\\
 +
basic-library/fast-route/1.3.txt · 最終更新: 2020/07/14 15:36 by y2sunlight