Last active
October 20, 2024 07:16
-
-
Save okumurakengo/cf65ea5d8aacb485b61b8cbe30480f1c to your computer and use it in GitHub Desktop.
簡易 php ルーティング
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| RewriteEngine On | |
| RewriteCond %{REQUEST_URI} !(\.png|\.jpg|\.webp|\.gif|\.jpeg|\.zip|\.css|\.svg|\.js|\.pdf)$ | |
| RewriteRule (.*) routes.php [QSA,L] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| namespace App; | |
| /** | |
| * Class Router | |
| */ | |
| class Router | |
| { | |
| /** | |
| * @param string $route | |
| * @param callable $callback | |
| * @return void | |
| */ | |
| private static function route(string $route, callable $callback): void | |
| { | |
| $request_url = filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL); | |
| $request_url = strtok($request_url, '?'); | |
| $request_url = rtrim($request_url, '/'); | |
| $request_url_parts = explode('/', $request_url); | |
| $route = rtrim($route, '/'); | |
| $route_parts = explode('/', $route); | |
| if ($request_url_parts === $route_parts) { | |
| $callback(); | |
| exit; | |
| } | |
| } | |
| /** | |
| * @param string $route | |
| * @param callable $callback | |
| * @return void | |
| */ | |
| public static function get(string $route, callable $callback): void | |
| { | |
| if ($_SERVER['REQUEST_METHOD'] == 'GET') { | |
| self::route($route, $callback); | |
| } | |
| } | |
| /** | |
| * @param string $route | |
| * @param callable $callback | |
| * @return void | |
| */ | |
| public static function post(string $route, callable $callback): void | |
| { | |
| if ($_SERVER['REQUEST_METHOD'] == 'POST') { | |
| self::route($route, $callback); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| use App\Controllers\FooController; | |
| use App\Controllers\BarController; | |
| use App\Router; | |
| require __DIR__ . '/../vendor/autoload.php'; | |
| Router::get('/foo/view', [FooController::class, 'view']); | |
| Router::post('/bar/edit', [BarController::class, 'edit']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment