PHPフレームワークのシンプルなルーター
路由的功能就是分发请求到不同的控制器,基于的原理就是正则匹配。接下来呢,我们实现一个简单的路由器,实现的能力是对于静态的路由(没占位符的),正确调用callback。
对于有占位符的路由,正确调用callback时传入占位符参数,譬如对于路由:/user/{id},当请求为/user/23时,传入参数$args结构为
[ 'id' => '23' ]
大致思路
我们需要把每个路由的信息管理起来:http方法($method),路由字符串($route),回调($callback),因此需要一个addRoute方法,另外提供短方法get,post(就是把$method写好)
对于/user/{id}这样的有占位符的路由字符串,把占位符要提取出来,然后占位符部分变成正则字符串
实现
Route.php类
<?phpnamespace SalamanderRoute;class Route { /** @var string */ public $httpMethod; /** @var string */ public $regex; /** @var array */ public $variables; /** @var mixed */ public $handler; /** * Constructs a route (value object). * * @param string $httpMethod * @param mixed $handler * @param string $regex * @param array $variables */ public function __construct($httpMethod, $handler, $regex, $variables) { $this->httpMethod = $httpMethod; $this->handler = $handler; $this->regex = $regex; $this->variables = $variables; } /** * Tests whether this route matches the given string. * * @param string $str * * @return bool */ public function matches($str) { $regex = '~^' . $this->regex . '$~'; return (bool) preg_match($regex, $str); } }
Dispatcher.php
<?php/** * User: salamander * Date: 2017/11/12 * Time: 13:43 */namespace SalamanderRoute;class Dispatcher { /** @var mixed[][] */ protected $staticRoutes = []; /** @var Route[][] */ private $methodToRegexToRoutesMap = []; const NOT_FOUND = 0; const FOUND = 1; const METHOD_NOT_ALLOWED = 2; /** * 提取占位符 * @param $route * @return array */ private function parse($route) { $regex = '~^(?:/[a-zA-Z0-9_]*|/\{([a-zA-Z0-9_]+?)\})+/?$~'; if(preg_match($regex, $route, $matches)) { // 去掉full match array_shift($matches); return [ preg_replace('~{[a-zA-Z0-9_]+?}~', '([a-zA-Z0-9_]+)', $route), $matches, ]; } throw new \LogicException('register route failed, pattern is illegal'); } /** * 注册路由 * @param $httpMethod string | string[] * @param $route * @param $handler */ public function addRoute($httpMethod, $route, $handler) { $routeData = $this->parse($route); foreach ((array) $httpMethod as $method) { if ($this->isStaticRoute($routeData)) { $this->addStaticRoute($httpMethod, $routeData, $handler); } else { $this->addVariableRoute($httpMethod, $routeData, $handler); } } } private function isStaticRoute($routeData) { return count($routeData[1]) === 0; } private function addStaticRoute($httpMethod, $routeData, $handler) { $routeStr = $routeData[0]; if (isset($this->staticRoutes[$httpMethod][$routeStr])) { throw new \LogicException(sprintf( 'Cannot register two routes matching "%s" for method "%s"', $routeStr, $httpMethod )); } if (isset($this->methodToRegexToRoutesMap[$httpMethod])) { foreach ($this->methodToRegexToRoutesMap[$httpMethod] as $route) { if ($route->matches($routeStr)) { throw new \LogicException(sprintf( 'Static route "%s" is shadowed by previously defined variable route "%s" for method "%s"', $routeStr, $route->regex, $httpMethod )); } } } $this->staticRoutes[$httpMethod][$routeStr] = $handler; } private function addVariableRoute($httpMethod, $routeData, $handler) { list($regex, $variables) = $routeData; if (isset($this->methodToRegexToRoutesMap[$httpMethod][$regex])) { throw new \LogicException(sprintf( 'Cannot register two routes matching "%s" for method "%s"', $regex, $httpMethod )); } $this->methodToRegexToRoutesMap[$httpMethod][$regex] = new Route( $httpMethod, $handler, $regex, $variables ); } public function get($route, $handler) { $this->addRoute('GET', $route, $handler); } public function post($route, $handler) { $this->addRoute('POST', $route, $handler); } public function put($route, $handler) { $this->addRoute('PUT', $route, $handler); } public function delete($route, $handler) { $this->addRoute('DELETE', $route, $handler); } public function patch($route, $handler) { $this->addRoute('PATCH', $route, $handler); } public function head($route, $handler) { $this->addRoute('HEAD', $route, $handler); } /** * 分发 * @param $httpMethod * @param $uri */ public function dispatch($httpMethod, $uri) { $staticRoutes = array_keys($this->staticRoutes[$httpMethod]); foreach ($staticRoutes as $staticRoute) { if($staticRoute === $uri) { return [self::FOUND, $this->staticRoutes[$httpMethod][$staticRoute], []]; } } $routeLookup = []; $index = 1; $regexes = array_keys($this->methodToRegexToRoutesMap[$httpMethod]); foreach ($regexes as $regex) { $routeLookup[$index] = [ $this->methodToRegexToRoutesMap[$httpMethod][$regex]->handler, $this->methodToRegexToRoutesMap[$httpMethod][$regex]->variables, ]; $index += count($this->methodToRegexToRoutesMap[$httpMethod][$regex]->variables); } $regexCombined = '~^(?:' . implode('|', $regexes) . ')$~'; if(!preg_match($regexCombined, $uri, $matches)) { return [self::NOT_FOUND]; } for ($i = 1; '' === $matches[$i]; ++$i); list($handler, $varNames) = $routeLookup[$i]; $vars = []; foreach ($varNames as $varName) { $vars[$varName] = $matches[$i++]; } return [self::FOUND, $handler, $vars]; } }
配置
nginx.conf重写到index.php
location / { try_files $uri $uri/ /index.php$is_args$args; # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } composer.json自动载入 { "name": "salmander/route", "require": {}, "autoload": { "psr-4": { "SalamanderRoute\\": "SalamanderRoute/" } }}
composer.json自动载入
{ "name": "salmander/route", "require": {}, "autoload": { "psr-4": { "SalamanderRoute\\": "SalamanderRoute/" } }
最终使用
index.php
<?phpinclude_once 'vendor/autoload.php';use SalamanderRoute\Dispatcher; $dispatcher = new Dispatcher(); $dispatcher->get('/', function () { echo 'hello world'; }); $dispatcher->get('/user/{id}', function ($args) { echo "user {$args['id']} visit"; });// Fetch method and URI from somewhere$httpMethod = $_SERVER['REQUEST_METHOD']; $uri = $_SERVER['REQUEST_URI'];// 去掉查询字符串if (false !== $pos = strpos($uri, '?')) { $uri = substr($uri, 0, $pos); } $routeInfo = $dispatcher->dispatch($httpMethod, $uri);switch ($routeInfo[0]) { case Dispatcher::NOT_FOUND: echo '404 not found'; break; case Dispatcher::FOUND: $handler = $routeInfo[1]; $vars = $routeInfo[2]; $handler($vars); break; }
看了上面的这个案例大家应该对PHP实现简单路由器,有更清楚的认识吧,后期我们还会继续推出相关文章,大家有任何问题都可以踊跃发言,
相关推荐:
以上がPHPフレームワークのシンプルなルーターの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









PHP 8.4 では、いくつかの新機能、セキュリティの改善、パフォーマンスの改善が行われ、かなりの量の機能の非推奨と削除が行われています。 このガイドでは、Ubuntu、Debian、またはその派生版に PHP 8.4 をインストールする方法、または PHP 8.4 にアップグレードする方法について説明します。

Visual Studio Code (VS Code とも呼ばれる) は、すべての主要なオペレーティング システムで利用できる無料のソース コード エディター (統合開発環境 (IDE)) です。 多くのプログラミング言語の拡張機能の大規模なコレクションを備えた VS Code は、

あなたが経験豊富な PHP 開発者であれば、すでにそこにいて、すでにそれを行っていると感じているかもしれません。あなたは、運用を達成するために、かなりの数のアプリケーションを開発し、数百万行のコードをデバッグし、大量のスクリプトを微調整してきました。

このチュートリアルでは、PHPを使用してXMLドキュメントを効率的に処理する方法を示しています。 XML(拡張可能なマークアップ言語)は、人間の読みやすさとマシン解析の両方に合わせて設計された多用途のテキストベースのマークアップ言語です。一般的にデータストレージに使用されます

JWTは、JSONに基づくオープン標準であり、主にアイデンティティ認証と情報交換のために、当事者間で情報を安全に送信するために使用されます。 1。JWTは、ヘッダー、ペイロード、署名の3つの部分で構成されています。 2。JWTの実用的な原則には、JWTの生成、JWTの検証、ペイロードの解析という3つのステップが含まれます。 3. PHPでの認証にJWTを使用する場合、JWTを生成および検証でき、ユーザーの役割と許可情報を高度な使用に含めることができます。 4.一般的なエラーには、署名検証障害、トークンの有効期限、およびペイロードが大きくなります。デバッグスキルには、デバッグツールの使用とロギングが含まれます。 5.パフォーマンスの最適化とベストプラクティスには、適切な署名アルゴリズムの使用、有効期間を合理的に設定することが含まれます。

文字列は、文字、数字、シンボルを含む一連の文字です。このチュートリアルでは、さまざまな方法を使用してPHPの特定の文字列内の母音の数を計算する方法を学びます。英語の母音は、a、e、i、o、u、そしてそれらは大文字または小文字である可能性があります。 母音とは何ですか? 母音は、特定の発音を表すアルファベットのある文字です。大文字と小文字など、英語には5つの母音があります。 a、e、i、o、u 例1 入力:string = "tutorialspoint" 出力:6 説明する 文字列「TutorialSpoint」の母音は、u、o、i、a、o、iです。合計で6元があります

静的結合(静的::) PHPで後期静的結合(LSB)を実装し、クラスを定義するのではなく、静的コンテキストで呼び出しクラスを参照できるようにします。 1)解析プロセスは実行時に実行されます。2)継承関係のコールクラスを検索します。3)パフォーマンスオーバーヘッドをもたらす可能性があります。

PHPの魔法の方法は何ですか? PHPの魔法の方法には次のものが含まれます。1。\ _ \ _コンストラクト、オブジェクトの初期化に使用されます。 2。\ _ \ _リソースのクリーンアップに使用される破壊。 3。\ _ \ _呼び出し、存在しないメソッド呼び出しを処理します。 4。\ _ \ _ get、dynamic属性アクセスを実装します。 5。\ _ \ _セット、動的属性設定を実装します。これらの方法は、特定の状況で自動的に呼び出され、コードの柔軟性と効率を向上させます。
